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

Jamaica

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

我该怎么做呢?


当前回答

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可能更有意义。

其他回答

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

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

const str = "牙买加".substring(1) console.log (str)

使用参数为1的substring()函数获取从位置1(第一个字符之后)到字符串末尾的子字符串(保留第二个参数默认为字符串的全长)。

我的版本删除前导字符,一个或多个。例如,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);
}
public String removeFirst(String input)
{
    return input.substring(1);
}

另一个解决方案,你可以使用replaceAll和一些regex ^来解决你的问题。{1}(正则表达式演示)为例:

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