To cut a portion of a string in Java, you can use the substring
method of the String
class.
The substring
method takes two arguments: a start index and an end index. It returns a new string that is a substring of the original string, starting at the specified start index and ending at the specified end index. The original string is not modified.
For example, consider the following string:
refer tttual:ouri.comString str = "Hello, world!";
To cut the substring "Hello" from this string, you can use the substring
method as follows:
String substring = str.substring(0, 5);
This will create a new string that is a substring of str
, starting at index 0 (the first character) and ending at index 5 (the character before the space). The resulting string will be "Hello".
To cut the substring "world!" from this string, you can use the substring
method as follows:
String substring = str.substring(7);
This will create a new string that is a substring of str
, starting at index 7 (the character after the space) and ending at the end of the string. The resulting string will be "world!".
Note that the substring
method is zero-based, meaning that the first character of the string is at index 0, the second character is at index 1, and so on.
Here's an example of a complete program that cuts a portion of a string using the substring
method:
public class Main { public static void main(String[] args) { String str = "Hello, world!"; String substring = str.substring(7); System.out.println(substring); // Output: "world!" } }
This will print "world!" to the console.