Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace character in StringBuilder [duplicate]

Tags:

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 '/' ?

like image 716
java baba Avatar asked May 16 '13 04:05

java baba


People also ask

How do I replace a character in StringBuilder?

replace() method replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.

Is StringBuilder replace faster?

Replace() was faster by about 20% every time swapping out 8-10 letter words. Try it for yourself if you want your own empirical evidence.

How do I remove the last character of a StringBuilder in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.

Can we append character in StringBuilder?

append(char a): This is an inbuilt method in Java which is used to append the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuilder sequence.


1 Answers

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("-", "/");
like image 145
MadProgrammer Avatar answered Sep 30 '22 09:09

MadProgrammer