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

Jamaica

我想删除字符串的第一个字符,然后返回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);
}

其他回答

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,其中包含当前包含在该序列中的字符的子序列。

子字符串从指定的开头开始,扩展到索引末尾的字符- 1。

它有两种形式。首先是

字符串子字符串(int FirstIndex)

这里,FirstIndex指定子字符串所在的索引 开始。此表单返回以。开始的子字符串的副本 FirstIndex并运行到调用字符串的末尾。

String子字符串(int FirstIndex, int endIndex)

这里,FirstIndex指定开始索引,endIndex指定 停止点。返回的字符串包含所有的字符 从开始索引到结束索引,但不包括结束索引。

例子

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

我的版本删除前导字符,一个或多个。例如,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);
}

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

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

# #芬兰湾的科特林 它工作得很好。

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