I have a StringBuilder and want to use replace method for a character. code given below
StringBuilder sb = new StringBuilder();
sb.append("01-02-2013");
How can i replace '-' with '/' ?
I have a StringBuilder and want to use replace method for a character. code given below
StringBuilder sb = new StringBuilder();
sb.append("01-02-2013");
How can i replace '-' with '/' ?
If don't want to convert the StringBuilder
to a String
or you need to keep using it/preserve it, then you could do something like this...
for (int index = 0; index < sb.length(); index++) {
if (sb.charAt(index) == '-') {
sb.setCharAt(index, '/');
}
}
If you don't care then you could do something like...
String value = sb.toString().replace("-", "/");
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 approch is
sb.toString().replaceAll("-", "/");
You should have searched a little bit about this.
Anyways, when starting to program in java, the best way to know what you can do with java in-built objects is to go to the javadoc of that class and there you will get to know plenty of thing.
In your case, you'll find your answer here : StringBuilder javadoc
Use replace
method.
Try replacing the characters directly to the string itself.
sb.append(("blah-blah").replace('-', '_'));
Would output
blah_blah