java 在android中将CharSequence第一个字母更改为大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3100526/
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 00:21:37  来源:igfitidea点击:

changing CharSequence first letter to upper case in android

javaandroidstringuppercase

提问by yoav.str

it may seem simple but it posses lots of bugs I tried this way:

它可能看起来很简单,但它有很多我尝试过的错误:

 String s = gameList[0].toString();
s.replaceFirst(String.valueOf(s.charAt(0)),String.valueOf(Character.toUpperCase(s.charAt(0))) );

and it throws an exception

它抛出一个异常

another try i had was :

我的另一个尝试是:

String s = gameList[0].toString();
char c = Character.toUpperCase(gameList[0].charAt(0));
gameList[0] = s.subSequence(1, s.length());

rhis one also throws an Exception

rhis one 也抛出异常

回答by Pentium10

/**
 * returns the string, the first char lowercase
 *
 * @param target
 * @return
 */
public final static String asLowerCaseFirstChar(final String target) {

    if ((target == null) || (target.length() == 0)) {
        return target; // You could omit this check and simply live with an
                       // exception if you like
    }
    return Character.toLowerCase(target.charAt(0))
            + (target.length() > 1 ? target.substring(1) : "");
}

/**
 * returns the string, the first char uppercase
 *
 * @param target
 * @return
 */
public final static String asUpperCaseFirstChar(final String target) {

    if ((target == null) || (target.length() == 0)) {
        return target; // You could omit this check and simply live with an
                       // exception if you like
    }
    return Character.toUpperCase(target.charAt(0))
            + (target.length() > 1 ? target.substring(1) : "");
}

回答by MartynOfEngland

. . . or do it all in an array. Here's something similar.

. . . 或者在一个数组中完成所有操作。这里有类似的东西。

    String titleize(String source){
        boolean cap = true;
        char[]  out = source.toCharArray();
        int i, len = source.length();
        for(i=0; i<len; i++){
            if(Character.isWhitespace(out[i])){
                cap = true;
                continue;
            }
            if(cap){
                out[i] = Character.toUpperCase(out[i]);
                cap = false;
            }
        }
        return new String(out);
    }

回答by polygenelubricants

On String being immutable

关于 String 是不可变的

Regarding your first attempt:

关于你的第一次尝试:

String s = gameList[0].toString();
s.replaceFirst(...);

Java strings are immutable. You can't invoke a method on a string instance and expect the method to modify that string. replaceFirstinstead returns a newstring. This means that these kinds of usage are wrong:

Java 字符串是不可变的。您不能在字符串实例上调用方法并期望该方法修改该字符串。replaceFirst而是返回一个字符串。这意味着这些类型的用法是错误的:

s1.trim();
s2.replace("x", "y");

Instead, you'd want to do something like this:

相反,你想要做这样的事情:

s1 = s1.trim();
s2 = s2.replace("x", "y");


As for changing the first letter of a CharSequenceto uppercase, something like this works (as seen on ideone.com):

至于将 a 的第一个字母更改CharSequence为大写,类似这样的操作(如 ideone.com 所示):

    static public CharSequence upperFirst(CharSequence s) {
        if (s.length() == 0) {
            return s;
        } else {
            return Character.toUpperCase(s.charAt(0))
                + s.subSequence(1, s.length()).toString();
        }
    }
    public static void main(String[] args) {
        String[] tests = {
            "xyz", "123 abc", "x", ""
        };
        for (String s : tests) {
            System.out.printf("[%s]->[%s]%n", s, upperFirst(s));
        }
        // [xyz]->[Xyz]
        // [123 abc]->[123 abc]
        // [x]->[X]
        // []->[]

        StringBuilder sb = new StringBuilder("blah");
        System.out.println(upperFirst(sb));
        // prints "Blah"
    }

This of course will throw NullPointerExceptionif s == null. This is often an appropriate behavior.

这当然会抛出NullPointerExceptionif s == null。这通常是一种适当的行为。

回答by Herrera

I like to use this simpler solution for names, where toUp is an array of full names split by (" "):

我喜欢使用这个更简单的名称解决方案,其中 toUp 是一个由 (" ") 分割的全名数组:

for (String name : toUp) {
    result = result + Character.toUpperCase(name.charAt(0)) + 
             name.substring(1).toLowerCase() + " ";
}

And this modified solution could be used to uppercase only the first letter of a full String, again toUp is a list of strings:

并且这个修改后的解决方案可用于仅大写完整字符串的第一个字母,同样 toUp 是一个字符串列表:

for (String line : toUp) {
    result = result + Character.toUpperCase(line.charAt(0)) + 
             line.substring(1).toLowerCase();
}

Hope this helps.

希望这可以帮助。