如何将字符串转换为标题情况的android?字符串、转换为、如何将、情况

2023-09-07 04:10:51 作者:作业被我养得白白的

我搜索高和低,但只能找到这种类型的问题间接引用。当开发一个Android应用程序,如果你已经进入用户的字符串,如何才能将其转换为标题情况下(即让每一个字大写的第一个字母)?我宁愿不导入全库(比如Apache的WordUtils)。

I searched high and low but could only find indirect references to this type of question. When developing an android application, if you have a string which has been entered by the user, how can you convert it to title case (ie. make the first letter of each word upper case)? I would rather not import a whole library (such as Apache's WordUtils).

推荐答案

我得到了一些三分球从这里开始:Android,need使我的ListView每个单词大写的第一个字母,但最后,推出自己的解决方案(注意,这种方法假定所有单词由单个空格字符,这是罚款,我需要分隔)

I got some pointers from here: Android,need to make in my ListView the first letter of each word uppercase, but in the end, rolled my own solution (note, this approach assumes that all words are separated by a single space character, which was fine for my needs):

String[] words = input.getText().toString().split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
    sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
    for (int i = 1; i < words.length; i++) {
        sb.append(" ");
        sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
    }
}
String titleCaseValue = sb.toString();

...其中输入一个EditText视图。这也有利于设置输入类型的视图,以便它默认为标题情况下无论如何:

...where input is an EditText view. It is also helpful to set the input type on the view so that it defaults to title case anyway:

input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);