java 为什么在使用 StringBuffer 后无法使用 toLowerCase()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10096170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:36:23  来源:igfitidea点击:

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

javastring

提问by Coffee

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

我在Java中读到,String是不可变的,所以我们不能真正直观地使用toLowerCase,即原始字符串未经修改:

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

> "ABC"

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

但即使使用 StringBuffer(支持可变字符串)也不起作用

StringBuffer so = new StringBuffer("PoP");

so.toLowerCase()

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

I appreciate any tips or advice.

我感谢任何提示或建议。

回答by Bozho

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

好吧,它没有。你必须使用.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 StringBuilderto StringBuffer

最后-喜欢StringBuilderStringBuffer

回答by EarlB

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

这个函数比使用“String lowercase = sb.toString().toLowerCase();”快20%左右 :

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;
}