how to substring in java

https:‮.www//‬lautturi.com
how to substring in java

To get a substring from a string in Java, you can use the substring method of the String class.

The substring method has two overloads:

  • public String substring(int beginIndex): Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the end of this string.

  • public String substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

Here's an example of how you can use the substring method to get a substring from a string:

String input = "Hello, world!";

// Get the substring from index 6 to the end of the string
String substring1 = input.substring(6);
System.out.println(substring1); // Outputs "world!"

// Get the substring from index 0 to index 5 (the character at index 5 is not included)
String substring2 = input.substring(0, 5);
System.out.println(substring2); // Outputs "Hello"

This code will get two substrings from the input string using the substring method, and print them to the console.

Note that the substring method uses zero-based indexing, so the first character in the string has an index of 0.

You can also use the subSequence method of the CharSequence interface to get a substring from a string. The subSequence method has the same overloads as the substring method, and works in the same way.

Created Time:2017-11-01 20:43:01  Author:lautturi