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

问题描述 投票:0回答:7

我在最近的Java项目中遇到了麻烦。我试图从字符串中只读出字符串“white”。无论我尝试什么方法,最后的“_”始终存在。

    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);
java string
7个回答
0
投票

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

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

2
投票

substring不修改原始对象。

使用

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

1
投票

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

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

0
投票

使用lastIndexOf

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

0
投票

你认为复杂 - 你为什么需要更换?您可以使用子字符串实现相同的功能

第一个声明

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

第二个声明

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

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


0
投票

你只需要改变第3行。

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

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


0
投票

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

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

将打印出来

Merry Christmas
© www.soinside.com 2019 - 2024. All rights reserved.