如何在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()
.
String my_new_str = my_str.replace("&", "&");
(都替换所有出现的内容; replaceAll
允许使用正则表达式.)
(Both replace all occurrences; replaceAll
allows use of regex.)
这篇关于如何在Java中替换字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!