Java - removing first character of a string
To remove the first character of a string in Java, you can use the substring()
method of the String
class. The substring()
method extracts a part of a string and returns it as a new string.
Here is an example of how you can use the substring()
method to remove the first character of a string:
String str = "Hello";
str = str.substring(1); // str is now "ello"
In this example, the substring()
method extracts the characters of the string starting at index 1 and ending at the end of the string. This removes the first character (the character at index 0) of the string.
You can also use the substring()
method to remove the first n
characters of a string by specifying the ending index as n
.
For example:
String str = "Hello";
str = str.substring(2); // str is now "llo"
This code removes the first two characters of the string.
Keep in mind that the substring()
method does not modify the original string, but rather returns a new string with the specified characters removed. If you want to modify the original string, you need to assign the result of the substring()
method back to the original string.
I hope this helps! Let me know if you have any other questions.