在Java中,我有一个字符串:

Jamaica

我想删除字符串的第一个字符,然后返回amaica

我该怎么做呢?


当前回答

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

其他回答

可以使用String类的substring方法,该方法只接受开头索引,并返回以指定索引处的字符开始并扩展到字符串末尾的子字符串。

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

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.

这对性能有许多影响。每次你“修改”一个字符串,你实际上是在创建一个新的字符串,所有的开销(内存分配和垃圾收集)。因此,如果你想对一个字符串进行一系列的修改,并且只关心最终的结果(一旦你“修改”了中间的字符串,它们就会死),那么使用StringBuilder或StringBuffer可能更有意义。

使用substring()并给出要从前面修剪的字符数。

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

答:“amaica”

我的版本删除前导字符,一个或多个。例如,String str1 = "01234",当去掉前导'0'时,结果将是"1234"。对于字符串str2 = "000123",结果仍然是"123"。对于字符串str3 = "000",结果将是空字符串:""。在将数值字符串转换为数字时,这种功能通常很有用。与regex (replaceAll(…))相比,该解决方案的优点是速度要快得多。这在处理大量字符串时非常重要。

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

我遇到了这样一种情况,我不仅要删除第一个字符(如果它是#的话),还要删除第一组字符。

字符串myString = ###Hello World可以作为起点,但我只想保留Hello World。这可以按照以下方法完成。

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

对于OP的情况,用if替换while,效果也很好。