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 '/' ?
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.
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.
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.
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.
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("-", "/");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With