从字符串中删除最后一个字符

时间:2017-12-21 01:53:24

标签: java string

我在最近的Java项目中遇到了麻烦。我试图只是字符串"白色"来自String。无论我尝试什么方法,最后一个" _"永远都是。

    String questionText = "The white house is _white_";
    String correctResponse = questionText.replace(questionText.substring(0, questionText.indexOf("_")+1), "");
    correctResponse.substring(0,correctResponse.length()-1);
    System.out.println(correctResponse);

7 个答案:

答案 0 :(得分:2)

substring不要修改原始对象。

使用

 correctResponse = correctResponse.substring(0, correctResponse.length() - 1);

答案 1 :(得分:1)

我会使用正则表达式对下划线之间的所有内容进行分组,然后String.replaceAll(String, String)实际删除除组之外的所有内容。像,

String correctResponse = questionText.replaceAll(".+\\s+_(.+)_", "$1"); // white

答案 2 :(得分:0)

使用lastIndexOf

String correctResponse = questionText.replace(questionText.substring(questionText.indexOf("_"), questionText.lastIndexOf("_")+1), "");

答案 3 :(得分:0)

如果你想要的字符串总是在下划线之间(或者至少在一个下划线之后),你可以只拆分字符串并在索引1处获取子字符串:

String correctResponse = questionText.split("_")[1];

答案 4 :(得分:0)

您认为复杂 - 为什么需要更换?您可以使用子字符串

实现相同的功能

第一句话

String correctResponse = questionText.substring(questionText.indexOf("_")+1)
// ==> correctResponse = "white_"

第二个陈述

correctResponse = correctResponse.substring(0, correctResponse.indexOf("_"))
// ==> correctResponse = "white"

正如@neuo指出的那样,substring不会改变字符串..

答案 5 :(得分:0)

您只需要更改第3行。

原线: correctResponse.substring(0,correctResponse.length() - 1);

正确的线条: correctResponse = correctResponse.substring(0,correctResponse.length() - 1);

答案 6 :(得分:0)

如果使用正则表达式,则不必检查索引边界。

String string = "Merry Christmas!".replaceAll(".$", "");
System.out.println(string);

将打印出来

Merry Christmas
相关问题