|NO.Z.00026|——————————|BigDataEnd|——|Java&核心类库.V11|——|Java.v11|string类.v11|子字符串获取|
一、string类中子字符串的获取:方法声明
方法声明 | 功能介绍 |
String substring(intbeginIndex, int endIndex) |
返回字符串中从下标beginIndex(包括) 开始到endIndex(不包括)结束的子字符串 |
String substring(intbeginIndex) | 返回字符串中从下标beginIndex(包括) 开始到字符串结尾的子字符串 |
### --- 案例题目
~~~ ——> 提示用户从键盘输入一个字符串和一个字符,输出该字符(不含)后面的所有子字符串。
二、编译打印
package com.yanqi.task12;
import java.util.Scanner;
public class SubStringTest {
public static void main(String[] args) {
// 1.构造String类型的对象并打印
String str1 = new String("Happy Wife, Happy Life!");
System.out.println("str1 = " + str1); // Happy Wife, Happy Life!
// 2.获取字符串中的一部分内容并打印
// 表示从当前字符串中下标12开始获取子字符串
String str2 = str1.substring(12);
System.out.println("str2 = " + str2); // Happy Life!
// 可以取到6但是取不到10
String str3 = str1.substring(6, 10);
System.out.println("str3 = " + str3); // Wife
System.out.println("---------------------------------------------------------");
// 3.获取输入字符串中从输入字符起的子字符串内容
System.out.println("请输入一个字符串:");
Scanner sc = new Scanner(System.in);
String str4 = sc.next();
System.out.println("请输入一个字符:");
String str5 = sc.next();
// 从str4中查找str5第一次出现的索引位置
int pos = str4.indexOf(str5);
System.out.println("pos = " + pos);
// 根据该位置获取子字符串
String str6 = str4.substring(pos+1);
System.out.println("获取到的子字符串是:" + str6);
}
}
三、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=52271:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task12.SubStringTest
str1 = Happy Wife, Happy Life!
str2 = Happy Life!
str3 = Wife
---------------------------------------------------------
请输入一个字符串:
123
请输入一个字符:
234
pos = -1
获取到的子字符串是:123
Process finished with exit code 0
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
——W.S.Landor
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通