删除String的最后两个字符

The*_*ook 51 java string substring

如何删除05简单字符串的最后两个字符?

简单:

"apple car 05"
Run Code Online (Sandbox Code Playgroud)

String[] lineSplitted = line.split(":");
String stopName = lineSplitted[0];
String stop =   stopName.substring(0, stopName.length() - 1);
String stopEnd = stopName.substring(0, stop.length() - 1);
Run Code Online (Sandbox Code Playgroud)

拆分前的原始线":"

apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16
Run Code Online (Sandbox Code Playgroud)

Ank*_*hal 84

减去最后空间的基础-2-3基础.

 public static void main(String[] args) {
        String s = "apple car 05";
        System.out.println(s.substring(0, s.length() - 2));
    }
Run Code Online (Sandbox Code Playgroud)

产量

apple car
Run Code Online (Sandbox Code Playgroud)

  • 为什么 Java 不想清理这个功能?字符串解析广泛应用于各种规模的组织中。在 Python 中,它就像 `s[:-2]` 一样简单。就是这样。 (3认同)

Isu*_*ana 23

使用String.substring(beginIndex,endIndex)

str.substring(0, str.length() - 2);
Run Code Online (Sandbox Code Playgroud)

子字符串从指定的beginIndex开始并扩展到index处的字符(endIndex - 1)


mas*_*d.m 5

您可以使用以下方法删除最后一个n字符 -

public String removeLast(String s, int n) {
    if (null != s && !s.isEmpty()) {
        s = s.substring(0, s.length()-n);
    }
    return s;
}
Run Code Online (Sandbox Code Playgroud)