How to replace character in string in Java?

Using Java, I want to go through lines of text and replace all ampersand ( & ) characters with a reference to the XML & .

I look through the lines of text, and then each word in the text with the Scanner. Then I use CharacterIterator to iterate over each character of the word. However, how can I replace a character? First, strings are immutable objects. Secondly, I want to replace the character ( & ) with several characters ( amp&; ). How do I approach this?

 CharacterIterator it = new StringCharacterIterator(token); for(char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) { if(ch == '&') { } } 
+60
java replace
Aug 05 '09 at 17:02
source share
10 answers

Try String.replace() use String.replace() or String.replaceAll() .

 String my_new_str = my_str.replace("&", "&"); 

(Both replace all occurrences; replaceAll allows the use of regular expressions.)

+111
Aug 05 '09 at 17:04
source share

Simple answer:

 token = token.replace("&", "&"); 

Despite the name compared to replaceAll, the substitute does replaceAll, it just does not use the regular expression, which seems to be here (both in terms of performance and in terms of good practice), does not use regular ones when they have special requirements for characters that you will not pay attention to).

The answer to Sean Bright is probably as good as it is worth considering in terms of performance, if you don't have any additional target requirement for benchmarking performance and performance, if you already know that this code is a performance hot spot if this is your question. coming from. This, of course, does not deserve descending slopes. Just use StringBuilder instead of StringBuffer if you don't need synchronization.

So there is a somewhat deeper potential problem here. Character escaping is a known issue that many libraries address. You might want to consider packing the data in the CDATA section into XML, or you may prefer to use the XML library (including the one that comes with the JDK) to actually generate the XML correctly (so that it handles the encoding).

Apache also has a screen library as part of Commons Lang.

+88
Aug 05 '09 at 17:58
source share
 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("&amp;"); break; case '<': s.append("&lt;"); break; case '>': s.append("&gt;"); break; default: s.append(ch); break; } } token = s.toString(); 
+14
Aug 05 '09 at 17:06
source share

You can also check to make sure that you are not replacing an event that has already been replaced. For this you can use a regex with a negative forecast.

For example:

 String str = "sdasdasa&amp;adas&dasdasa"; str = str.replaceAll("&(?!amp;)", "&amp;"); 

This will result in the string " sdasdasa&amp;adas&amp;dasdasa ".

The regex pattern "& (?! Amp;)" basically says: match any occurrence of '&' that doesn't follow 'amp;'.

+7
Aug 05 '09 at 17:49
source share

Just create a string containing all the data in question, and then use String.replaceAll () as shown below.

 String result = yourString.replaceAll("&", "&amp;"); 
+4
Aug 05 '09 at 17:06
source share

Escaping strings can be tricky - especially if you want to enable unicode. I believe that XML is one of the easiest formats / languages ​​to exit, but still. I would recommend taking a look at the StringEscapeUtils class in Apache Commons Lang and its convenient escapeXml method.

+1
Aug 05 '09 at 17:43
source share

Try this code. You can replace any character with another specified character. Here I tried to replace the letter 'a' with the character "-" for the string string "abcdeaa"

OutPut β†’ _ 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"); } } 
+1
Aug 20 '17 at 5:01
source share

Check out this method.

0
Aug 05 '09 at 17:07
source share

If you use Spring, you can simply call HtmlUtils.htmlEscape(String input) , which will handle the '&' to '&' translation.

0
Aug 05 '09 at 17:35
source share
 //I think this will work, you don't have to replace on the even, it 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); } } } 
0
Sep 08 '16 at 3:37
source share



All Articles