简体   繁体   English

java中的字符串替换方法问题

[英]String replace method issue in java

My problem is to replace only the last occurrence of a character in the string with another character.我的问题是只用另一个字符替换字符串中最后一次出现的字符。 When I used the String.replace(char1, char2), it replaces all the occurrences of the character in the string.当我使用 String.replace(char1, char2) 时,它会替换字符串中出现的所有字符。

For example, I have an address string like例如,我有一个地址字符串,如

String str = "Addressline1,Addressline2,City,State,Country,"; . .

I need to replace the occurrence of ',' at the end of the string with '.'.我需要将字符串末尾出现的 ',' 替换为 '.'。

My code to replace the character is我替换字符的代码是

str = str.replace(str.charAt(str.lastIndexOf(",")),'.');

After replacing, the string looks like:替换后,字符串如下所示:

Addressline1.Addressline2.City.State.Country. Addressline1.Addressline2.City.State.Country。

Is there the problem in Java SDK?. Java SDK 有问题吗? If yes, how to resolve it?如果是,如何解决?

You should use String.replaceAll which use regex您应该使用使用正则表达式的String.replaceAll

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

The $ mean the end of the String $表示字符串的结尾

The Java replace function has a method declaration of: Java 替换函数有一个方法声明:

public String replace(char oldChar, char newChar)

According to the docs replace will:根据文档replace将:

Return a new string resulting from replacing all occurrences of oldChar in this string with newChar .通过用newChar替换此字符串中所有出现的oldChar ,返回一个新字符串。

So your code:所以你的代码:

str.charAt(str.lastIndexOf(","))

Will clearly return the character , .将明确返回字符, replace will then replace all instances of the oldChar , with the newChar . replace然后将替换的所有实例oldChar ,newChar . . . This explains the behavior you were seeing.这解释了您所看到的行为。

The solution that @ScaryWombat beat me to is your best option: @ScaryWombat 击败我的解决方案是您的最佳选择:

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

Since, in regular expression terms, $ denotes the end of a String.因为,在正则表达式术语中, $表示字符串的结尾。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM