Java - Removing First Character of a String

Java - Removing First Character of a String

In Java, I have a String:

Jamaica

I would like to remove the first character of the string and then return amaica

How would I do this?

0

14 Answers

Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).

"Jamaica".substring(1);
3
public String removeFirstChar(String s){
   return s.substring(1);
}
1

Use substring() and give the number of characters that you want to trim from front.

String value = "Jamaica";
value = value.substring(1);

Answer: "amaica"

0

In Java, remove leading character only if it is a certain character

Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.

String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

Prints:

blankstring
foobar
moobar
Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.