Remove the first 2 characters of a string in Java
In this tutorial, we are going to learn about how to remove the first 2 characters of a string in Java.
Remove the first 2 characters
To remove the first 2 characters of a string, we can use the built-in substring() method in Java.
Here is an example:
String str = "12Hello";
String result = str.substring(2);
System.out.println(result);
Output:
"Hello"
In the example above, we have passed 2
as argument to the substring() method. so it begins the extraction at index position 2
and extracts to the end of a string.
Syntax of substring() method
substring(startindex, stopindex)
It begins the extraction at startIndex and goes upto the stopindex-1, if we don’t provide the endIndex it begins the extraction at specified index extracts upto to the end of a string.
The substring()
method doesn’t mutates the original string, instead of it creates a new one with the extracted characters.