java - 如果字符串以字符串结尾,则从字符串中删除半冒号 [英] java - removing semi colon from a string if the string ends with it
问题描述
我有一个要求,如果它出现在字符串的末尾(仅在结尾处),我需要删除分号。我试过以下代码。但它仍然没有被取代。任何人都可以在行号中的以下代码中告诉我需要更改的内容
(我在这里引用了代码如何从Java中的特定字符串中删除特定字符?)
I have a requirement in which I need to remove the semicolon if it is present at the end of the String(only at the end). I have tried the following code. But still it is not getting replaced. Can anyone please tell what I need to change in the following code in the line number
(I referred the code from here How do I delete specific characters from a particular String in Java?)
public static void main(String[] args) {
String text = "wherabouts;";
System.out.println("SSS "+text.substring(text.length()-1));
if(text.substring(text.length()-1) == ";"){
text.replaceAll(";", "");
}
System.out.println("TEXT : "+text);
}
推荐答案
text.replaceAll(";", "");
由于Java中的字符串是不可变的,所以 replaceALl()
方法不进行就地替换,而是返回一个新的修改后的字符串。因此,您需要将返回值存储在其他字符串中。另外,要匹配最后的分号,您需要在之后使用
$
量词;
Since Strings in Java are immutable, so replaceALl()
method doesn't do the in-place replacement, rather it returns a new modified string. So, you need to store the return value in some other string. Also, to match the semi-colon at the end, you need to use $
quantifier after ;
text = text.replaceAll(";$", "");
$
表示自字符串结束你想要替换最后的分号
..
$
denotes the end of the string since you want to replace the last semi-colon
..
如果你不使用 $
,它将替换你的字符串中的所有;
..
If you don't use $
, it will replace all the ;
from your strings..
或,对于你的工作,你可以简单地使用它,如果你想删除最后一个;
:
Or, for your job, you can simply use this, if you want to remove the last ;
:
if (text.endsWith(";")) {
text = text.substring(0, text.length() - 1);
System.out.println(text);
}
更新:并且,如果还有更多半-colons结尾:
UPDATE: And, if there are more semi-colons at the end:
text = text.replaceAll(";+$", "");
这篇关于java - 如果字符串以字符串结尾,则从字符串中删除半冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!