如何在 Java 中替换字符串中的字符? [英] How do I replace a character in a string in Java?
问题描述
使用 Java,我想遍历文本行并用 XML 实体引用 &
替换所有与符号 (&
).
Using Java, I want to go through the lines of a text and replace all ampersand symbols (&
) with the XML entity reference &
.
我使用 Scanner 类扫描文本的行,然后扫描文本中的每个单词.然后我使用 CharacterIterator
来遍历单词的每个字符.但是,如何替换字符?首先,字符串是不可变的对象.其次,我想用几个字符(amp&;
)替换一个字符(&
).我应该如何处理这个问题?
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?
CharacterIterator it = new StringCharacterIterator(token);
for(char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
if(ch == '&') {
}
}
推荐答案
尝试使用 String.replace()
或 String.replaceAll()
代替.
Try using String.replace()
or String.replaceAll()
instead.
String my_new_str = my_str.replace("&", "&");
(都替换所有出现的;replaceAll
允许使用正则表达式.)
(Both replace all occurrences; replaceAll
allows use of regex.)
这篇关于如何在 Java 中替换字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!