如何在 Java 中替换字符串中的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1234510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace a character in a string in Java?
提问by user42155
Using Java, I want to go through the lines of a text and replace all ampersand symbols (&
) with the XML entity reference &
.
使用 Java,我想遍历文本行并将所有&
与符号 ( ) 替换为 XML 实体引用&
。
I scan the lines of the text and then each word in the text with the Scanner class. Then I use the CharacterIterator
to iterate over each characters of the word. However, how can I replace the character? First, Strings are immutable objects. Second, I want to replace a character (&
) with several characters(amp&;
). How should I approach this?
我扫描文本的行,然后使用 Scanner 类扫描文本中的每个单词。然后我使用CharacterIterator
来遍历单词的每个字符。但是,如何替换字符?首先,字符串是不可变的对象。其次,我想&
用几个字符( amp&;
)替换一个字符( )。我应该如何处理这个问题?
CharacterIterator it = new StringCharacterIterator(token);
for(char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
if(ch == '&') {
}
}
回答by Amber
Try using String.replace()
or String.replaceAll()
instead.
尝试使用String.replace()
或String.replaceAll()
代替。
String my_new_str = my_str.replace("&", "&");
(Both replace all occurrences; replaceAll
allows use of regex.)
(两者都替换所有出现的;replaceAll
允许使用正则表达式。)
回答by Sean Bright
StringBuilder s = new StringBuilder(token.length());
CharacterIterator it = new StringCharacterIterator(token);
for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
switch (ch) {
case '&':
s.append("&");
break;
case '<':
s.append("<");
break;
case '>':
s.append(">");
break;
default:
s.append(ch);
break;
}
}
token = s.toString();
回答by Taylor Leese
Just create a string that contains all of the data in question and then use String.replaceAll()like below.
只需创建一个包含所有相关数据的字符串,然后使用String.replaceAll()如下所示。
String result = yourString.replaceAll("&", "&");
回答by Adamski
If you're using Spring you can simply call HtmlUtils.htmlEscape(String input)
which will handle the '&' to '&' translation.
如果您使用的是 Spring,您可以简单地调用HtmlUtils.htmlEscape(String input)
它来处理“&”到“&”的翻译。
回答by Chris Vest
Escaping strings can be tricky- especially if you want to take unicode into account. I suppose XML is one of the simpler formats/languages to escape but still. I would recommend taking a look at the StringEscapeUtils class in Apache Commons Lang, and its handy escapeXmlmethod.
转义字符串可能很棘手- 特别是如果您想考虑 unicode。我认为 XML 是更简单的格式/语言之一,但仍然可以转义。我建议您查看 Apache Commons Lang 中的 StringEscapeUtils 类及其方便的escapeXml方法。
回答by Robert Durgin
You may also want to check to make sure your not replacing an occurrence that has already been replaced. You can use a regular expression with negative lookahead to do this.
您可能还需要检查以确保您没有替换已被替换的事件。您可以使用带有负前瞻的正则表达式来执行此操作。
For example:
例如:
String str = "sdasdasa&adas&dasdasa";
str = str.replaceAll("&(?!amp;)", "&");
This would result in the string "sdasdasa&adas&dasdasa
".
这将导致字符串“ sdasdasa&adas&dasdasa
”。
The regex pattern "&(?!amp;)" basically says: Match any occurrence of '&' that is not followed by 'amp;'.
正则表达式模式 "&(?!amp;)" 基本上是说:匹配任何后面没有跟有 'amp;' 的 '&'。
回答by Yishai
The simple answer is:
简单的答案是:
token = token.replace("&", "&");
Despite the name as compared to replaceAll, replace does do a replaceAll, it just doesn't use a regular expression, which seems to be in order here (both from a performance and a good practice perspective - don't use regular expressions by accident as they have special character requirements which you won't be paying attention to).
尽管名称与 replaceAll 相比,replace 确实做了一个 replaceAll,它只是不使用正则表达式,这在这里似乎是有序的(从性能和良好实践的角度来看 - 不要偶然使用正则表达式因为他们有特殊的性格要求,你不会注意到)。
Sean Bright's answer is probably as good as is worth thinking about from a performance perspective absent some further target requirement on performance and performance testing, if you already know this code is a hot spot for performance, if that is where your question is coming from. It certainly doesn't deserve the downvotes. Just use StringBuilder instead of StringBuffer unless you need the synchronization.
如果您已经知道此代码是性能的热点,如果这就是您的问题的来源,则 Sean Bright 的答案可能与从性能角度考虑的一样好,没有对性能和性能测试的进一步目标要求。它当然不值得投反对票。除非需要同步,否则只需使用 StringBuilder 而不是 StringBuffer 。
That being said, there is a somewhat deeper potential problem here. Escaping characters is a known problem which lots of libraries out there address. You may want to consider wrapping the data in a CDATA section in the XML, or you may prefer to use an XML library (including the one that comes with the JDK now) to actually generate the XML properly (so that it will handle the encoding).
话虽如此,这里有一个更深层次的潜在问题。转义字符是一个已知问题,许多图书馆都在解决这个问题。您可能需要考虑将数据包装在 XML 的 CDATA 部分中,或者您可能更喜欢使用 XML 库(包括现在 JDK 附带的库)来实际正确生成 XML(以便它处理编码)。
Apache also has an escaping libraryas part of Commons Lang.
Apache 还有一个转义库作为 Commons Lang 的一部分。
回答by user2125311
//I think this will work, you don't have to replace on the even, it's just an example.
public void emphasize(String phrase, char ch)
{
char phraseArray[] = phrase.toCharArray();
for(int i=0; i< phrase.length(); i++)
{
if(i%2==0)// even number
{
String value = Character.toString(phraseArray[i]);
value = value.replace(value,"*");
phraseArray[i] = value.charAt(0);
}
}
}
回答by chamzz.dot
Try this code.You can replace any character with another given character. Here I tried to replace the letter 'a'with "-"character for the give string "abcdeaa"
试试这个代码。你可以用另一个给定的字符替换任何字符。在这里,我尝试用“-”字符替换给定字符串“abcdeaa”的字母“a ”
OutPut -->_bcdef__
输出 -->_bcdef__
public class Replace {
public static void replaceChar(String str,String target){
String result = str.replaceAll(target, "_");
System.out.println(result);
}
public static void main(String[] args) {
replaceChar("abcdefaa","a");
}
}
回答by Atul Anand
String taskLatLng = task.getTask_latlng().replaceAll( "\(","").replaceAll("\)","").replaceAll("lat/lng:", "").trim();