Caffeinated
Caffeinated

Reputation: 12484

How come I can't use toLowerCase() after using a StringBuffer?

I read that in Java, String is immutable, so we can't really use toLowerCase intuitively, i.e the original string is unmodified:

String s = "ABC";
s.toLowerCase();

> "ABC"

But even using StringBuffer(which supports mutable Strings) does not work

StringBuffer so = new StringBuffer("PoP");

so.toLowerCase()

> Static Error: No method in StringBuffer has name 'toLowerCase'

I appreciate any tips or advice.

Upvotes: 2

Views: 19131

Answers (2)

EarlB
EarlB

Reputation: 131

This function is about 20% faster than using "String lowercase = sb.toString().toLowerCase();" :

public static StringBuilder StringBuilderLowerCase(StringBuilder pText) {
        StringBuilder pTextLower = new StringBuilder(pText);
        for (int idx = 0; idx < pText.length(); idx++) {
            char c = pText.charAt(idx);
            if (c >= 65 && c <= 65 + 27) {
                pTextLower.setCharAt(idx, (char) ((int) (pText.charAt(idx)) | 32));
            }
        }
        return pTextLower;
}

Upvotes: 1

Bozho
Bozho

Reputation: 597254

Well, it doesn't. You'd have to use .toString().toLowerCase():

String lowercase = sb.toString().toLowerCase();

If you want to be very strict about not creating unnecessary instances, you can iterate all characters, and lowercase them:

for (int i = 0; i < sb.length(); i++) {
   char c = sb.charAt(i);
   sb.setCharAt(i, Character.toLowerCase(c));
}

And finally - prefer StringBuilder to StringBuffer

Upvotes: 15

Related Questions