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

18

4

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

Russ

Posted 2012-09-12T11:47:51.043

Reputation: 1 682

when you wer knowing the answer then y did u asked a question here ? – Shruti – 2012-09-12T11:49:22.287

2

@Shruti: This behavior is by design. http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/

– SLaks – 2012-09-12T11:50:31.917

1@Shruti There's nothing wrong with answering your own questions. Stackoverflow isn't just for finding solutions to your own problems, the main point should be providing useful questions and answers for future users who have the same problem. – Anthony Grist – 2012-09-12T11:54:26.530

Answers

20

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

Codeversed

Posted 2012-09-12T11:47:51.043

Reputation: 6 445

1Very well done. Thanks. – dazed – 2017-08-04T15:08:54.333

16

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

Russ

Posted 2012-09-12T11:47:51.043

Reputation: 1 682

2if you have possibly several spaces, you can use split("\s+") (splits on 1 or more space) – njzk2 – 2012-09-12T12:10:52.023

10

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

SLaks

Posted 2012-09-12T11:47:51.043

Reputation: 672 943

Yes, but as I said, I didn't really want to import a whole library just for this. – Russ – 2012-09-12T12:02:50.890

2I'm upvoting this, even though it violates the parameters of the question. As the OP mentioned, this is the only stack overflow question that really addresses this problem on Android, and I think the possibility of using Apache commons should be mentioned in the answers section as an alternative, rather than just in passing in the question itself. – Kiirani – 2013-07-10T07:09:43.323

10

this helps you

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

Ankitkumar Makwana

Posted 2012-09-12T11:47:51.043

Reputation: 3 174

6

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

zeeshan

Posted 2012-09-12T11:47:51.043

Reputation: 2 437

3In Android, inputType can only be used with EditText, not with TextView – user1652110 – 2016-05-14T22:19:33.353

1TextView should probably be an EditText instead – Pratik Butani – 2016-05-15T03:54:46.870

2You are right about EditText, but this is where the Android doc points to. – zeeshan – 2016-05-15T15:53:33.393

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.

SafaOrhan

Posted 2012-09-12T11:47:51.043

Reputation: 336

This code assumes the input string is all lower case. To handle all upper case input you need to tweak the following line... buffer.append(ch); becomes buffer.append(Character.toLowerCase(ch)); in the 3rd branch of the main else statement. – Andrew Kelly – 2014-09-23T00:16:42.723

3

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

mossman252

Posted 2012-09-12T11:47:51.043

Reputation: 256

2

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.

gMale

Posted 2012-09-12T11:47:51.043

Reputation: 8 484

0

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

Ravindra Kushwaha

Posted 2012-09-12T11:47:51.043

Reputation: 3 331

0

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

Angel Koh

Posted 2012-09-12T11:47:51.043

Reputation: 5 724

0

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

ErickBergmann

Posted 2012-09-12T11:47:51.043

Reputation: 537

0

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

Rajesh Tiwari

Posted 2012-09-12T11:47:51.043

Reputation: 261