删除字符串的最后两个字符

Delete the last two characters of the String

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

简单:

"apple car 05"

代码

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

拆分前的原始行“:”

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

减去 -2-3 的基础,同时删除最后一个 space。

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

输出

apple car

使用String.substring(beginIndex, endIndex)

str.substring(0, str.length() - 2);

子字符串从指定的 beginIndex 开始,延伸到索引 (endIndex - 1) 处的字符

您可以使用substring函数:

s.substring(0,s.length() - 2));

对于第一个 0,您对 substring 说它必须从字符串的第一个字符开始,对于 s.length() - 2 它必须在前 2 个字符结束字符串结束。

有关 substring 函数的更多信息,请参见此处:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

这几乎是正确的,只需将您的最后一行更改为:

String stopEnd = stop.substring(0, stop.length() - 1); //replace stopName with stop.

您可以替换最后两行;

String stopEnd =   stopName.substring(0, stopName.length() - 2);

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

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

另一种解决方案是使用某种 regex:

例如:

    String s = "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";
    String results=  s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
    System.out.println(results); // output 9
    System.out.println(results.length());// output "apple car"

您也可以试试下面的异常处理代码。这里有一个方法 removeLast(String s, int n)(它实际上是 masud.m 答案的修改版本)。您必须提供 String 以及要从最后一个 removeLast(String s, int n) 函数中删除多少 char 。如果必须从最后删除的 char 的数量大于给定的 String 长度,那么它会抛出带有自定义消息的 StringIndexOutOfBoundException -

public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{

        int strLength = s.length();

        if(n>strLength){
            throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
        }

        else if(null!=s && !s.isEmpty()){

            s = s.substring(0, s.length()-n);
        }

        return s;

    }