从字符串中删除除最后n个字符之外的所有字符

时间:2014-09-15 11:10:25

标签: java android indexing runtime-error substring

我正在尝试删除除最后10个字符之外的所有文本,但在android

中收到错误
 09-15 16:22:58.146: E/AndroidRuntime(13630): java.lang.StringIndexOutOfBoundsException: length=228; index=263

但是当我在单独的类中尝试它时它正在使用java。 这是我试过的?任何人都可以告诉我,如果在android中有任何关于子串的问题吗?

String allchar = 
"PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklklj
kljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljs
fdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68
Alias12345";

    String  number = "";
    String reqtext = allchar.replaceAll("\\s+","");
    number = reqtext.substring(reqtext.length()-10 );
    System.out.println(number);

3 个答案:

答案 0 :(得分:1)

如果substring()不起作用,您可以尝试手动执行:

String allchar = 
"PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklklj
kljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljs
fdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68
Alias12345";

    StringBuilder number = new StringBuilder();
    String reqtext = allchar.replaceAll("\\s+","");
    for(int i = reqtext.length()-10; i < reqtext.length(); i++)
    {
        number.append(reqtext.charAt(i));
    }
    System.out.println(number.toString());

答案 1 :(得分:0)

    String allchar = "PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklkljkljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljsfdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68Alias12345";
String  number = "";
String reqtext = allchar.replaceAll("\\s+","");
number = reqtext.substring(reqtext.length()-10, reqtext.length());
System.out.println(number);

此代码在android中适用于我。

答案 2 :(得分:0)

避免声明如此多的变量,请尝试使用:

number = allchar.substring(allchar.length()-10, allchar.length());