publicstaticvoidmain(String[]args){String a="abcd-efg";String a1=a.substring(a.lastIndexOf("-")+1);String a2=a.substring(0,a.indexOf("-"));System.out.println(a1);//efgSystem.out.println(a2);//abcdString b="620303197010141212";if(b.length()==18){String sex=b.substring(16,17);...
运行程序后,我们可以看到indexOf方法的执行时间明显短于substring方法,从而验证了前面所述的性能差异。 总结 在Java中,String的substring和indexOf方法是两个常用的字符串操作方法,但它们的性能并不相同。由于substring方法会创建新的String对象,可能会产生一定的性能开销,而indexOf方法只是进行字符比较,并不会创建新的对象...
例如,如果字符串长度小于3,直接截取最后3位可能会导致StringIndexOutOfBoundsException异常: publicclassSafeSubstringExample{publicstaticvoidmain(String[]args){Stringstr="Hi";StringlastThreeChars=safeSubstring(str,3);System.out.println("截取结果是: "+lastThreeChars);}publicstaticStringsafeSubstring(Stringstr,...
String str2="123"; System.out.println( str1.indexOf(str2)); 输出结果:1 indexOf(String str, int fromIndex) 从指定的索引开始搜索,返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。 例如 String str1="012345012345"; String str2="123"; System.out.println( str1.indexOf(str2,2...
substring(int beginIndex, int endIndex):从指定的beginIndex位置开始截取字符串,直到字符串末尾。与上一个构造函数不同的是,这个构造函数可以指定截取字符串的长度。如果endIndex超过字符串的长度,那么将抛出StringIndexOutOfBoundsException异常。下面是一个简单的示例代码:public class SubstringDemo { public static...
1、通过subString()方法来进行字符串截取,返回字符串中的子字符串,在java中有两种用法 第一种,传递一个参数: publicString substring(intbeginIndex)//该子字符串从指定索引处的字符开始,直到此字符串末尾。public String substring(int beginIndex)//该子字符串从指定索引处的字符开始,直到此字符串末尾。
1、Substring方法的定义:Java中的String类提供了名为substring的方法,用于从源字符串中截取出指定部分的子字符串。2、Substring方法的作用:Substring方法主要用于以下几个方面:提取指定位置的子字符串;根据起始索引和结束索引截取子字符串;根据起始索引截取到字符串末尾的子字符串。二、Substring方法的参数含义和用法 ...
【Java核心基础】Java中substring方法核心总结 - 程序员古德 下面列举了使用substring方法的一些场景,如下代码:publicclassSubstringExample{ publicstaticvoidmain(String[] args){ String originalString = "Hello, World! This is a substring example."; // 1. 提取从索引0开始的子字符串 String substrin...
在Java中,substring() 方法是 String 类的成员方法,用于从一个字符串中提取子串。它有两个变种:substring(int beginIndex):从指定的开始索引(包括开始索引)截取到字符串的末尾。substring(int beginIndex, int endIndex):从指定的开始索引(包括开始索引)截取到结束索引(不包括结束索引)。下面是两种形式的基本...
Java中的`substring`方法用于截取字符串的子串。以下是其使用方法:1. 语法:String substring(int beginIndex, int endIndex)2. 参数说明 * `beginIndex`:必需。子串的起始索引(包含)。索引从开始计数。例如,字符串`"Hello World"`的索引对应于字符`H`。* `endIndex`:必需。子串的结束索引(不包含)。索引...