294

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?

1
  • If this question gets enough upvotes, it will be hot hot hot. Oct 11, 2023 at 21:58

14 Answers 14

450

const str = "Jamaica".substring(1)
console.log(str)

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).

3
  • 34
    Its important to note that this doesn't actually remove the character from the string -- it gives you a new string that has all the characters of the old string except the first one. There's no way to actually modify a string.
    – Chris Dodd
    Sep 7, 2016 at 23:07
  • The link appears to be no longer valid. Try the following link instead: substring(int) Aug 21, 2018 at 15:15
  • 1
    Yeah, if you want to remove the first n characters of a string variable you do this: variable = variable.substring(n); Mar 15, 2019 at 19:52
85
public String removeFirstChar(String s){
   return s.substring(1);
}
1
  • 12
    If you're going to define a new function, at least choose a suitable name like removeFirst().
    – moinudin
    Dec 21, 2010 at 20:41
64

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

Java, remove all the instances of a character anywhere in a string:

String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"

Java, remove the first instance of a character anywhere in a string:

String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
2
  • 6
    DRY: header = header.substring(header.startsWith("#") ? 1 : 0); Apr 5, 2016 at 19:29
  • 4
    Or with regex: header = header.replaceFirst("^#",""); Apr 5, 2016 at 19:30
61

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

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

Answer: "amaica"

1
  • This is better than the answers that pass 2 args to substring(). I'm not sure why they complicate it. Oct 11, 2023 at 19:56
19

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);
15

substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.

The substring begins at the specified start and extends to the character at index end - 1.

It has two forms. The first is

  1. String substring(int FirstIndex)

Here, FirstIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at FirstIndex and runs to the end of the invoking string.

  1. String substring(int FirstIndex, int endIndex)

Here, FirstIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.

Example

   String str = "Amiyo";
   // prints substring from index 3
   System.out.println("substring is = " + str.substring(3)); // Output 'yo'
12

you can do like this:

String str = "Jamaica";
str = str.substring(1, title.length());
return str;

or in general:

public String removeFirstChar(String str){
   return str.substring(1, title.length());
}
11
public String removeFirst(String input)
{
    return input.substring(1);
}
11

The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.

This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.

7

You can simply use substring().

String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)

The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".

5

I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.

String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.

while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
    myString = myString.substring(1, myString.length());
}

For OP's case, replace while with if and it works aswell.

1
  • 1
    There will be a problem if myString == "#" because the String will be out of bounds at some point. To prevent this, you could do (!myString.isEmpty() && myString.charAt(0))
    – Christian
    Jun 26, 2017 at 11:30
2

Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :

String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
1

My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.

 public static String removeLeadingChar(String str, char ch) {
    int idx = 0;
    while ((idx < str.length()) && (str.charAt(idx) == ch))
        idx++;
    return str.substring(idx);
}
0

##KOTLIN #Its working fine.

tv.doOnTextChanged { text: CharSequence?, start, count, after ->
            val length = text.toString().length
            if (length==1 && text!!.startsWith(" ")) {
                tv?.setText("")
            }
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.