public class SubstringExample { public static void main(String[] args) { String originalString = "Hello, World!";// 截取从索引位置2开始的剩余部分,即 "llo, World!"String substring1 = originalString.substring(2);System.out.println(substring1);// 截取从索引位置7到索引位置12之间的部分,即 "Wo...
publicclassSafeSubstringExample{publicstaticvoidmain(String[]args){Stringstr="Hi";StringlastThreeChars=safeSubstring(str,3);System.out.println("截取结果是: "+lastThreeChars);}publicstaticStringsafeSubstring(Stringstr,intnum){intlength=str.length();if(length<num){returnstr;// 返回原字符串}returnst...
【Java核心基础】Java中substring方法核心总结 - 程序员古德 下面列举了使用substring方法的一些场景,如下代码:publicclassSubstringExample{ publicstaticvoidmain(String[] args){ String originalString = "Hello, World! This is a substring example."; // 1. 提取从索引0开始的子字符串 String substrin...
publicclassSubstringExample{publicstaticvoidmain(String[]args){Stringurl="Stringhost=getHost(url);System.out.println("Host: "+host);}publicstaticStringgetHost(Stringurl){intfirstIndex=url.indexOf("/");intsecondIndex=url.indexOf("/",firstIndex+1);intthirdIndex=url.indexOf("/",secondIndex+1)...
在Java中,substring() 方法是 String 类的成员方法,用于从一个字符串中提取子串。它有两个变种:substring(int beginIndex):从指定的开始索引(包括开始索引)截取到字符串的末尾。substring(int beginIndex, int endIndex):从指定的开始索引(包括开始索引)截取到结束索引(不包括结束索引)。下面是两种形式的基本...
public class SubstringExample { public static void main(String[] args) { String str = "Hello World";String subStr = str.substring(6, 11); // 从索引6开始(包含)到索引10结束(不包含)System.out.println(subStr); // 输出 "World"} } 在上面的示例中,我们使用`substring`方法从字符串`"Hello...
Let us see the full java code for the example stated above. public class SubstringExampleWithBothIndex { public static void main(String[] args) { String name = "codeRolls.com"; String result = name.substring(4, 9); System.out.println(result); } } Output: Rolls Note: substring(int...
Example 1: Java substring() With Only Start Index classMain{publicstaticvoidmain(String[] args){ String str1 ="program";// 1st character to the last character System.out.println(str1.substring(0));// program // 4th character to the last characterSystem.out.println(str1.substring(3));/...
In the following example, we are getting the substring from index position 6. Assertions.assertEquals("World",str.substring(6)); 3.IndexOutOfBoundsException As mentioned earlier, if we pass an invalid index (such asnegative indexvalue) that does not exist in the character array, or the begin...
1. Basic substring example demonstrates both the variants of this method Before we start to see some interesting substring method examples, let’s start with a simple example that demonstrates the usage of this method. publicclassJavaExample{publicstaticvoidmain(Stringargs[]){Stringstr=newString("...