Using deleteCharAt() to delete first or last character You can use deleteCharAt(0) to remove the first character and deleteCharAt(length - 1) to remove the last character from String in Java, as shown in our second example.
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);
public String removeFirstChar(String s){
return s.substring(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"
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
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
You can use the substring method of the String
class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
public String removeFirst(String input)
{
return input.substring(1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With