Replace character in StringBuilder

I have a StringBuilder and you want to use the replace method on a character. code below

StringBuilder sb = new StringBuilder(); sb.append("01-02-2013"); 

How can I replace '-' with '/'?

+4
source share
4 answers

If you do not want to convert StringBuilder to String or you need to continue to use it / save, then you can do something like this ...

 for (int index = 0; index < sb.length(); index++) { if (sb.charAt(index) == '-') { sb.setCharAt(index, '/'); } } 

If you don't care, you can do something like ...

 String value = sb.toString().replace("-", "/"); 
+10
source

Try this way

 StringBuilder sb = new StringBuilder(); sb.append("01-02-2013"); sb.replace(sb.indexOf("-"), sb.indexOf("-")+1, "/") ; sb.replace(sb.indexOf("-"), sb.indexOf("-")+1, "/") ; System.out.println(sb.toString()); 

Better agree

 sb.toString().replaceAll("-", "/"); 
+6
source

Try replacing characters directly with a string.

 sb.append(("blah-blah").replace('-', '_')); 

Will output

 blah_blah 
+1
source

You should know a little about it.

In any case, when you start programming in java, the best way to find out what you can do with embedded Java objects is to go to the javadoc of this class, and there you will learn a lot of things.

In your case, you will find your answer here: StringBuilder javadoc

Use the replace method.

+1
source

Source: https://habr.com/ru/post/1481090/


All Articles