如何在android中将字符串转换为标题大小写?

时间:2012-09-12 11:47:51

标签: android string title-case

我搜索了高低,但只能找到对这类问题的间接引用。在开发一个Android应用程序时,如果你有一个用户输入的字符串,你如何将它转换为标题大小写(即,使每个单词的大写字母为大写)?我宁愿不导入整个库(例如Apache的WordUtils)。

14 个答案:

答案 0 :(得分:28)

将它放在文本实用程序类中:

public static String toTitleCase(String str) {

    if (str == null) {
        return null;
    }

    boolean space = true;
    StringBuilder builder = new StringBuilder(str);
    final int len = builder.length();

    for (int i = 0; i < len; ++i) {
        char c = builder.charAt(i);
        if (space) {
            if (!Character.isWhitespace(c)) {
                // Convert to title case and switch out of whitespace mode.
                builder.setCharAt(i, Character.toTitleCase(c));
                space = false;
            }
        } else if (Character.isWhitespace(c)) {
            space = true;
        } else {
            builder.setCharAt(i, Character.toLowerCase(c));
        }
    }

    return builder.toString();
}

答案 1 :(得分:16)

我从这里得到了一些指示:Android,need to make in my ListView the first letter of each word uppercase,但最后,推出了我自己的解决方案(请注意,这种方法假定所有单词都由一个空格字符分隔,这对我的需求很好):

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();

...其中input是EditText视图。在视图上设置输入类型也很有帮助,因此无论如何都默认为标题大小写:

input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);

答案 2 :(得分:11)

您正在寻找Apache的WordUtils.capitalize() method

答案 3 :(得分:11)

这有助于你

EditText view = (EditText) find..
String txt = view.getText();
txt = String.valueOf(txt.charAt(0)).toUpperCase() + txt.substring(1, txt.length());

答案 4 :(得分:8)

在XML中,您可以这样做:

android:inputType="textCapWords"

检查其他选项的参考,例如句子案例,所有大写字母等:

http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

答案 5 :(得分:6)

如果您不想导入整个班级,请使用WordUtils.capitalize()方法。

public static String capitalize(String str) {
    return capitalize(str, null);
}

public static String capitalize(String str, char[] delimiters) {
    int delimLen = (delimiters == null ? -1 : delimiters.length);
    if (str == null || str.length() == 0 || delimLen == 0) {
        return str;
    }
    int strLen = str.length();
    StringBuffer buffer = new StringBuffer(strLen);
    boolean capitalizeNext = true;
    for (int i = 0; i < strLen; i++) {
        char ch = str.charAt(i);

        if (isDelimiter(ch, delimiters)) {
            buffer.append(ch);
            capitalizeNext = true;
        } else if (capitalizeNext) {
            buffer.append(Character.toTitleCase(ch));
            capitalizeNext = false;
        } else {
            buffer.append(ch);
        }
    }
    return buffer.toString();
}
private static boolean isDelimiter(char ch, char[] delimiters) {
    if (delimiters == null) {
        return Character.isWhitespace(ch);
    }
    for (int i = 0, isize = delimiters.length; i < isize; i++) {
        if (ch == delimiters[i]) {
            return true;
        }
    }
    return false;
}

希望它有所帮助。

答案 6 :(得分:3)

做这样的事情:

public static String toCamelCase(String s){
    if(s.length() == 0){
        return s;
    }
    String[] parts = s.split(" ");
    String camelCaseString = "";
    for (String part : parts){
        camelCaseString = camelCaseString + toProperCase(part) + " ";
    }
    return camelCaseString;
}

public static String toProperCase(String s) {
    return s.substring(0, 1).toUpperCase() +
            s.substring(1).toLowerCase();
}

答案 7 :(得分:2)

我遇到了同样的问题并用此解决了这个问题:

import android.text.TextUtils;
...

String[] words = input.split("[.\\s]+");

for(int i = 0; i < words.length; i++) {
    words[i] = words[i].substring(0,1).toUpperCase()
               + words[i].substring(1).toLowerCase();
}

String titleCase = TextUtils.join(" ", words);

注意,在我的情况下,我也需要删除句点。在“拆分”期间,可以在方括号之间插入任何需要用空格替换的字符。例如,以下内容最终将取代下划线,句号,逗号或空格:

String[] words = input.split("[_.,\\s]+");

当然,这可以通过"non-word character" symbol

更简单地完成
String[] words = input.split("\\W+");

值得一提的是,数字和连字符 ARE 被认为是“单词字符”,因此最后一个版本完全满足了我的需求,并希望能帮助其他人。

答案 8 :(得分:0)

请检查下面的解决方案,它既适用于多个字符串,也适用于单个字符串

 String toBeCapped = "i want this sentence capitalized";  
 String[] tokens = toBeCapped.split("\\s"); 

 if(tokens.length>0)
 {
   toBeCapped = ""; 

    for(int i = 0; i < tokens.length; i++)
    { 
     char capLetter = Character.toUpperCase(tokens[i].charAt(0)); 
     toBeCapped += " " + capLetter + tokens[i].substring(1, tokens[i].length()); 
    }
 }
 else
 {
  char capLetter = Character.toUpperCase(toBeCapped.charAt(0)); 
  toBeCapped += " " + capLetter + toBeCapped .substring(1, toBeCapped .length()); 
 }

答案 9 :(得分:0)

我简化了@Russ接受的答案,这样就不需要区分字符串数组中的第一个单词和其他单词。 (我在每个单词之后添加空格,然后在返回句子之前修剪句子)

public static String toCamelCaseSentence(String s) {

    if (s != null) {
        String[] words = s.split(" ");

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < words.length; i++) {
            sb.append(toCamelCaseWord(words[i]));
        }

        return sb.toString().trim();
    } else {
        return "";
    }
}

处理空字符串(句子中的多个空格)和字符串中的单个字母。

public static String toCamelCaseWord(String word) {
    if (word ==null){
        return "";
    }

    switch (word.length()) {
        case 0:
            return "";
        case 1:
            return word.toUpperCase(Locale.getDefault()) + " ";
        default:
            char firstLetter = Character.toUpperCase(word.charAt(0));
            return firstLetter + word.substring(1).toLowerCase(Locale.getDefault()) + " ";
    }
}

答案 10 :(得分:0)

我编写了一个基于Apache的WordUtils.capitalize()方法的代码。您可以将分隔符设置为正则表达式字符串。如果你想要&#34; of&#34;要跳过,只需将它们设置为分隔符。

batch_X = batch[0:4]

希望有助于:)

答案 11 :(得分:0)

使用此功能转换驼峰式数据

 public static String camelCase(String stringToConvert) {
        if (TextUtils.isEmpty(stringToConvert))
            {return "";}
        return Character.toUpperCase(stringToConvert.charAt(0)) +
                stringToConvert.substring(1).toLowerCase();
    }

答案 12 :(得分:0)

科特林-Android-标题保护套/骆驼保护套功能

.content-editable {
    position: absolute;
    top: 90px;
    text-align: right;
    width: 100%;
    font-size: 30px;
    color: #fff;
    border: 2px dashed gray;
  }

OR

fun toTitleCase(str: String?): String? {

        if (str == null) {
            return null
        }

        var space = true
        val builder = StringBuilder(str)
        val len = builder.length

        for (i in 0 until len) {
            val c = builder[i]
            if (space) {
                if (!Character.isWhitespace(c)) {
                    // Convert to title case and switch out of whitespace mode.
                    builder.setCharAt(i, Character.toTitleCase(c))
                    space = false
                }
            } else if (Character.isWhitespace(c)) {
                space = true
            } else {
                builder.setCharAt(i, Character.toLowerCase(c))
            }
        }

        return builder.toString()
    }

答案 13 :(得分:0)

如果您要查找标题案例格式, 此kotlin扩展功能可能会为您提供帮助。

fun String.toTitleCase(): String {
if (isNotEmpty()) {
    val charArray = this.toCharArray()
    return buildString {
        for (i: Int in charArray.indices) {
            val c = charArray[i]
            // start find space from 1 because it can cause invalid index of position if (-1)
            val previous = if (i > 0) charArray[(i - 1)] else null
            // true if before is space char
            val isBeforeSpace = previous?.let { Character.isSpaceChar(it) } ?: false
            // append char to uppercase if current index is 0 or before is space
            if (i == 0 || isBeforeSpace) append(c.toUpperCase()) else append(c)
            print("char:$c, \ncharIndex: $i, \nisBeforeSpace: $isBeforeSpace\n\n")
        }
        print("result: $this")
    }
} return this }

实现方式

data class User(val name :String){ val displayName: String get() = name.toTitleCase() }