How do I convert a string to title case in android?

左心房为你撑大大i 提交于 2019-11-30 13:41:24

问题


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).


回答1:


Put this in your text utilities class:

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



回答2:


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

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



回答3:


this helps you

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



回答4:


You're looking for Apache's WordUtils.capitalize() method.




回答5:


In the XML, you can do it like this:

android:inputType="textCapWords"

Check the reference for other options, like Sentence case, all upper letters, etc. here:

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




回答6:


Here is the WordUtils.capitalize() method in case you don't want to import the whole class.

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

Hope it helps.




回答7:


Just do something like this:

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



回答8:


I just had the same problem and solved it with this:

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

Note, in my case, I needed to remove periods, as well. Any characters that need to be replaced with spaces can be inserted between the square braces during the "split." For instance, the following would ultimately replace underscores, periods, commas or whitespace:

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

This, of course, can be accomplished much more simply with the "non-word character" symbol:

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

It's worth mentioning that numbers and hyphens ARE considered "word characters" so this last version met my needs perfectly and hopefully will help someone else out there.




回答9:


Please check the solution below it will work for both multiple string and also single string to

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



回答10:


I simplified the accepted answer from @Russ such that there is no need to differentiate the first word in the string array from the rest of the words. (I add the space after every word, then just trim the sentence before returning the sentence)

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

handles empty strings (multiple spaces in sentence) and single letter words in the String.

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()) + " ";
    }
}



回答11:


I wrote a code based on Apache's WordUtils.capitalize() method. You can set your Delimiters as a Regex String. If you want words like "of" to be skipped, just set them as a delimiter.

public static String capitalize(String str, final String delimitersRegex) {
    if (str == null || str.length() == 0) {
        return "";
    }

    final Pattern delimPattern;
    if (delimitersRegex == null || delimitersRegex.length() == 0){
        delimPattern = Pattern.compile("\\W");
    }else {
        delimPattern = Pattern.compile(delimitersRegex);
    }

    final Matcher delimMatcher = delimPattern.matcher(str);
    boolean delimiterFound = delimMatcher.find();

    int delimeterStart = -1;
    if (delimiterFound){
        delimeterStart = delimMatcher.start();
    }

    final int strLen = str.length();
    final StringBuilder buffer = new StringBuilder(strLen);

    boolean capitalizeNext = true;
    for (int i = 0; i < strLen; i++) {
        if (delimiterFound && i == delimeterStart) {
            final int endIndex = delimMatcher.end();

            buffer.append( str.substring(i, endIndex) );
            i = endIndex;

            if( (delimiterFound = delimMatcher.find()) ){
                delimeterStart = delimMatcher.start();
            }

            capitalizeNext = true;
        } else {
            final char ch = str.charAt(i);

            if (capitalizeNext) {
                buffer.append(Character.toTitleCase(ch));
                capitalizeNext = false;
            } else {
                buffer.append(ch);
            }
        }
    }
    return buffer.toString();
}

Hope that Helps :)




回答12:


Use this function to convert data in camel case

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



回答13:


Kotlin - Android - Title Case / Camel Case function

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

OR

fun camelCase(stringToConvert: String): String {
    if (TextUtils.isEmpty(stringToConvert)) {
        return "";
    }
    return Character.toUpperCase(stringToConvert[0]) +
            stringToConvert.substring(1).toLowerCase();
}


来源:https://stackoverflow.com/questions/12387492/how-do-i-convert-a-string-to-title-case-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!