Remove first character from a String in Java
This post will discuss how to remove the first character from a String in Java.
Since Strings are immutable in Java, you can’t remove any character from it. However, you can create a new instance of the string without the first character.
The standard solution to return a new string with the first character removed from it is using the substring() method with the beginning index 1. This will create a substring of the string from position 1 till its end.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Main { public static String removefirstChar(String str) { if (str == null || str.length() == 0) { return str; } return str.substring(1); } public static void main(String[] args) { String str = "ABC"; System.out.println(removefirstChar(str)); } } |
It is often needed to remove the first character only if it is a specific character. You can do so by checking if the string starts with the specific character before calling the substring() method. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Main { public static String removefirstChar(String str, String start) { if (str == null || str.length() == 0) { return str; } if (str.startsWith(start)) { return str.substring(1); } return str; } public static void main(String[] args) { String str = "ABC"; String start = "A"; System.out.println(removefirstChar(str, start)); } } |
That’s all about removing first character from a String in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)