java – 如果字符串以字符串结尾,则从字符串中删除半冒号

我有一个要求,如果它出现在String的末尾(仅在结尾),我需要删除分号。 我试过以下代码。 但它仍然没有被取代。 任何人都可以在行号中的以下代码中告诉我需要更改的内容
(我在这里引用了代码如何从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()方法不进行就地替换,而是返回一个新的修改后的字符串。 因此,您需要将返回值存储在其他字符串中。 另外,为了匹配最后的分号 ,你需要使用$ quantifier ;

 text = text.replaceAll(";$", ""); 

$表示字符串的结尾,因为你想要替换最后一个semi-colon

如果你不使用$ ,它将取代所有; 从你的字符串..

或者,对于你的工作,你可以简单地使用它,如果你想删除最后一个;

  if (text.endsWith(";")) { text = text.substring(0, text.length() - 1); System.out.println(text); } 

更新 :如果最后有更多的分号:

 text = text.replaceAll(";+$", ""); 

String modifiedText = text.replaceAll(";$", "");

要么

text = text.replaceAll(";$", "");

要么

 if (text.endsWith(";")) { text = text.substring(0, text.length() - 1); } 

注意

字符串是不可变的。 这意味着你无法改变它们。

因此,您必须重新分配文本或将其设置为新变量。

 text = text.replaceAll(";", ""); 

这里有一点额外的阅读http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html

你不应该忘记String是不可变的。 因此,每当您想要修改它时,您必须将结果分配给变量。

您需要的可能解决方案:

 if (text.endsWith(";") { text = text.substring(0, text.length() - 1); } 

java中的字符串是不可变的,因此replaceAll返回一个新字符串。

  text = text.replaceAll(";", ""); 
 if (text.endsWith(";")){ text = text.substring(0,text.length()-1); } 

您使用的是错误版本的String.substring ,您可以使用:

 text.substring(0, text.length() - 1) 

字符串是不可变的,因此在替换后将创建新的String。

 String newString = text.replace(";", ""); 

要么

 String newString = text.replaceAll(";$", ""); 

如果要使用substring()而不是charAt()请使用.equals()而不是==

 if(text.substring(text.length()-1).equals(";")) 

另外,重新分配您的文本变量:

 text = text.replaceAll(";", ""); 

您提供的代码中存在多个问题。

使用equals来比较对象。

 if(text.substring(text.length()-1).equals(";")) 

如果您只想替换最后一个字符,则不需要replaceAll。

这样做也是如此

 if(text.substring(text.length()-1).equals(";")) { text = text.substring(0, text.length()-1); } 

要么

 text = text.replaceAll(";", ""); 
 public static void main(String[] args) { String text_original = "wherabouts;"; char[] c = text_original.toCharArray(); System.out.println("TEXT original: "+ text_original); String text_new = c[text_original.length()-1] == ';' ? text_original.substring(0,text_original.length()-2) : text_original; System.out.println("TEXT new: "+text_new); } 

解决方案只有一个分号

 // Don't use regular expressions if you don't need to. if (text.endsWith(";")) { text = text.substring(0, text.length() - 1); } 

较慢的解决方案可能超过一个分号

 text.replaceAll(";+$", ""); 

此外,以下是您最初发布的代码的其他一些问题,以供参考。

 if(text.substring(text.length()-1) == ";"){ 

您无法将字符串与==进行比较。 相反,你必须将它们与.equals()进行比较。 这将正确写成...ength()-1).equals(";")

 text.replaceAll(";", ""); 

这将替换它找到的所有分号。 这意味着,如果你的字符串是some;thing; ,它会把它变成something ,但你只想删除最后一个分号,如下: some;thing 。 要正确执行此操作,您需要使用特殊的$字符查找字符串的结尾,如下所示:

 text.replaceAll(";$", "");