xxxxxxxxxx
// Example of extracting a substring in Java
String str = "Hello World";
int startIndex = 6; // index where the substring starts
int endIndex = 11; // index where the substring ends (exclusive)
String substring = str.substring(startIndex, endIndex);
System.out.println(substring); // Outputs "World"
xxxxxxxxxx
String s = "Let's Get This Bread";
String subString = s.substring(6, 9);
// (start index inclusive, end index exclusive)
// subString == "Get"
xxxxxxxxxx
class scratch{
public static void main(String[] args) {
String hey = "Hello World";
System.out.println( hey.substring(0, 5) );
// prints Hello;
}
}
xxxxxxxxxx
// substring(int begin, int end)
String n = "hello there general kenobi";
System.out.println(n.substring(6, 11));
// -> "there"
xxxxxxxxxx
// Suppose we want the first 4 chars of str
String a = str.substring(0, 4);
xxxxxxxxxx
String str = "Hello, World!";
int startIndex = 7; // index of the first character to include
int endIndex = 12; // index of the character following the last character to include
String subStr = str.substring(startIndex, endIndex);
System.out.println(subStr); // Output: World
xxxxxxxxxx
// Java code to demonstrate the
// working of substring(int begIndex, int endIndex)
// Driver Class
public class Substr2 {
// main function
public static void main(String args[])
{
// Initializing String
String Str = new String("https://achs-test.literatumonline.com/doi/10.1021/acs.jpca.3c04798#eulaContent");
// using substring() to extract substring
// returns geeks
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(0, Str.indexOf('#')));
}
}
xxxxxxxxxx
public class Substring {
public static void main(String[] args) {
String s = "Hello Scaler!";
/* Throws StringIndexOutOfBoundsException as endIndex is out of range of string s */
System.out.println(s.str.substring(1, 30));
}
}