Is there a method for String conversion to Title Case?
Asked Answered
F

22

127

Are there any built in methods available to convert a string into Title Case format?

Filippo answered 6/7, 2009 at 9:6 Comment(3)
Everyone reading this question: beware that many of the top voted answers here DO NOT WORK PROPERLY for all languages. You need an i18n-aware library for correct titlecasing, like ICU4J (see Daniel F's answer).Lurlene
Does this answer your question? How to capitalize the first character of each word in a stringBatrachian
I take back my duplicate question. That is specifically not title case, in that it leaves the case of non-initial letters of each word alone, rather than changing them to upper case. e.g. aBcD -> "ABcD", not "Abcd".Batrachian
M
130

Apache Commons StringUtils.capitalize() or Commons Text WordUtils.capitalize()

e.g: WordUtils.capitalize("i am FINE") = "I Am FINE" from WordUtils doc

Magocsi answered 6/7, 2009 at 9:9 Comment(6)
WordUtils.capitalizeFully() was better for me as it gives: WordUtils.capitalizeFully("i am FINE") = "I Am Fine"Retread
Just a small update, WordUtils is gone to Commons Text and is deprecated inside Commons LangShutout
Spring also has StringUtils.capitalise()Rickart
@Rickart do you mean capitalize()?Obscene
2021: WordUtils in Apache Commons is deprecated now. Use StringUtilsAustraloid
StringUtils.capitalize only caps the first character of the first word. WordUtils.capitalize or capitalizeFully create a title-case string (each word starts with a capital). There is no WordUtils in lang3 any more -- it was moved to text.Loxodromic
A
68

There are no capitalize() or titleCase() methods in Java's String class. You have two choices:

 StringUtils.capitalize(null)  = null
 StringUtils.capitalize("")    = ""
 StringUtils.capitalize("cat") = "Cat"
 StringUtils.capitalize("cAt") = "CAt"
 StringUtils.capitalize("'cat'") = "'cat'"
  • write (yet another) static helper method toTitleCase()

Sample implementation

public static String toTitleCase(String input) {
    StringBuilder titleCase = new StringBuilder(input.length());
    boolean nextTitleCase = true;

    for (char c : input.toCharArray()) {
        if (Character.isSpaceChar(c)) {
            nextTitleCase = true;
        } else if (nextTitleCase) {
            c = Character.toTitleCase(c);
            nextTitleCase = false;
        }

        titleCase.append(c);
    }

    return titleCase.toString();
}

Testcase

    System.out.println(toTitleCase("string"));
    System.out.println(toTitleCase("another string"));
    System.out.println(toTitleCase("YET ANOTHER STRING"));

outputs:

String
Another String
YET ANOTHER STRING
Airbrush answered 6/7, 2009 at 9:9 Comment(7)
This is a nice little routine, but it fails for the more general case in which Strings may represent names. In this case, capitalization would also need to occur after apostrophes and hyphens, too. Eg. O'Connor and J. Wilkes-Booth. Of course, other languages may have additional title case rules.Dolores
...If it were going to include that, wouldnt it need an entire dictionary lookup just to work out if the current word was a name? That seems a bit much for any one method.Anamorphosis
This code is almost fine because some names can have prepositons such as de, del, della, dei, da as in Maria del Carmen, Maria da Silva, Maria della Salute, etc. coderanch.com/t/35096/Programming/…Estipulate
Doesn't this break with apostrophe? What about O'Brian for example.Twofaced
Note: to avoid resizing of the internally used char[] in StringBuilder I suggest using new StringBuilder(input.length())Admiral
@Twofaced My idea was to provide an implementation for handling Java naming conventions, not for handling any kind of string representing names etc. Much more effort would be needed to properly handling all linguistic/regional differences for handling names.Airbrush
Please note, this home-grown solution misses most of the title case rules. capitalizemytitle.com Words like "a", "an", and "the" are not supposed to be capitalized. The second part of a hyphenated word should be. Others have pointed out that proper names retain their capitalization, such as "O'Connor" But this solution will likely meet the needs of most people stopping here. So still a good answer. Reader beware.Appraisal
D
43

If I may submit my take on the solution...

The following method is based on the one that dfa posted. It makes the following major change (which is suited to the solution I needed at the time): it forces all characters in the input string into lower case unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.

A major limitation of my routine is that it makes the assumption that "title case" is uniformly defined for all locales and is represented by the same case conventions I have used and so it is less useful than dfa's code in that respect.

public static String toDisplayCase(String s) {

    final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
                                                 // to be capitalized
    
    StringBuilder sb = new StringBuilder();
    boolean capNext = true;

    for (char c : s.toCharArray()) {
        c = (capNext)
                ? Character.toUpperCase(c)
                : Character.toLowerCase(c);
        sb.append(c);
        capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
    }
    return sb.toString();
}

TEST VALUES

a string

maRTin o'maLLEY

john wilkes-booth

YET ANOTHER STRING

OUTPUTS

A String

Martin O'Malley

John Wilkes-Booth

Yet Another String

Dolores answered 1/4, 2013 at 6:3 Comment(5)
will not work with ligatures like lj, whose uppercase is LJ but titlecase is Lj. Use Character.toTitleCase instead.Breakage
@mihi: also will not work with other specialized rules, eg. surnames such as McNamara or MacDonald.Dolores
but these cases can inherently not be fixed. Using the correct case conversion function (titlecase is supposed to be used to capitalize a word, and not uppercase, according to Unicode rules) can be done (and it's easy).Breakage
Wouldn't (Wouldn'T) this also cause "her's" to become "Her'S"?Mogador
It's true. This works well on name fields but, as you point out, not on general prose. It wouldn't even work well on all names, Vulcans in particular (T'Pau instead of T'pau).Dolores
Q
22

Use WordUtils.capitalizeFully() from Apache Commons.

WordUtils.capitalizeFully(null)        = null
WordUtils.capitalizeFully("")          = ""
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
Quirites answered 6/8, 2013 at 2:20 Comment(1)
Nice solution! Thanks! But this does not work 100 % of the time, as it also capitalizes e.g. "a" in this title: "This is a Title". See english.stackexchange.com/questions/14/…. Do you know of any library that deals with this?Foreboding
P
12

You can use apache commons langs like this :

WordUtils.capitalizeFully("this is a text to be capitalize")

you can find the java doc here : WordUtils.capitalizeFully java doc

and if you want to remove the spaces in between the worlds you can use :

StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")

you can find the java doc for String StringUtils.remove java doc

i hope this help.

Philippic answered 24/8, 2015 at 11:19 Comment(0)
H
10

If you want the correct answer according to the latest Unicode standard, you should use icu4j.

UCharacter.toTitleCase(Locale.US, "hello world", null, 0);

Note that this is locale sensitive.

Api Documentation

Implementation

Haroldharolda answered 28/6, 2016 at 10:5 Comment(5)
Also see the newer ICU4J API CaseMap: icu-project.org/apiref/icu4j/com/ibm/icu/text/…Lurlene
Also available in Android API level 24: developer.android.com/reference/android/icu/lang/…Lurlene
I tested it with the following: "alexander and the terrible, horrible, no good, very bad day, by judith viorst and ray cruz" I expected: "Alexander and the Terrible, Horrible, No Good, Very Bad Day, by Judith Viorst and Ray Cruz" But the actual result was: "Alexander And The Terrible, Horrible, No Good, Very Bad Day, By Judith Viorst And Ray Cruz" Does not work as expected. It just uppercase every word in a phrase, same as other builtin solutionsSorcha
@Sorcha You want an AI-based natural language processor. That's beyond the ability of most libraries mentioned here, and - I'd say - out of the scope of this question. "Title Case" means capitalising everything.Evars
@DavidLavender I agree that could be hard to achieve, but one thing is "Title Case" and another one is "Fully Capitalized", perhaps the name could be misleading, or at least it was in my case. en.wikipedia.org/wiki/Title_caseSorcha
P
8

Here's another take based on @dfa's and @scottb's answers that handles any non-letter/digit characters:

public final class TitleCase {

    public static String toTitleCase(String input) {

        StringBuilder titleCase = new StringBuilder(input.length());
        boolean nextTitleCase = true;

        for (char c : input.toLowerCase().toCharArray()) {
            if (!Character.isLetterOrDigit(c)) {
                nextTitleCase = true;
            } else if (nextTitleCase) {
                c = Character.toTitleCase(c);
                nextTitleCase = false;
            }
            titleCase.append(c);
        }

        return titleCase.toString();
    }

}

Given input:

MARY ÄNN O’CONNEŽ-ŠUSLIK

the output is

Mary Änn O’Connež-Šuslik

Pyoid answered 25/5, 2017 at 21:7 Comment(0)
E
3

This is something I wrote to convert snake_case to lowerCamelCase but could easily be adjusted based on the requirements

private String convertToLowerCamel(String startingText)
{
    String[] parts = startingText.split("_");
    return parts[0].toLowerCase() + Arrays.stream(parts)
                    .skip(1)
                    .map(part -> part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
                    .collect(Collectors.joining());
}
Exstipulate answered 14/4, 2016 at 11:15 Comment(1)
Your answer works like a charm, however, the solution doesn't seem to handle single word sequence, maybe an if condition should suffice.Fullmer
N
3

Use this method to convert a string to title case :

static String toTitleCase(String word) {
    return Stream.of(word.split(" "))
            .map(w -> w.toUpperCase().charAt(0) + w.toLowerCase().substring(1))
            .reduce((s, s2) -> s + " " + s2)
            .orElse("");
}
Nadinenadir answered 4/6, 2019 at 14:17 Comment(0)
E
2

Using Spring's StringUtils:

org.springframework.util.StringUtils.capitalize(someText);

If you're already using Spring anyway, this avoids bringing in another framework.

Evars answered 19/11, 2018 at 16:9 Comment(0)
H
1

I know this is older one, but doesn't carry the simple answer, I needed this method for my coding so I added here, simple to use.

public static String toTitleCase(String input) {
    input = input.toLowerCase();
    char c =  input.charAt(0);
    String s = new String("" + c);
    String f = s.toUpperCase();
    return f + input.substring(1);
}
Hindmost answered 21/11, 2015 at 14:11 Comment(0)
G
1

you can very well use

org.apache.commons.lang.WordUtils

or

CaseFormat

from Google's API.

Groome answered 31/3, 2016 at 21:3 Comment(2)
It would be useful to add the method and an example.April
CaseFormat only has formats typically used in program identifiers (UpperCamel, lower-hypen, UPPER_UNDERSCORE, etc.) and only supports ASCII text. It would not work well for converting to Title Case.Batrachian
T
1

I had this problem and i searched for it then i made my own method using some java keywords just need to pass String variable as parameter and get output as proper titled String.

public class Main
{
  public static void main (String[]args)
  {
    String st = "pARVeEN sISHOsIYA";
    String mainn = getTitleCase (st);
      System.out.println (mainn);
  }


  public static String getTitleCase(String input)
  {
    StringBuilder titleCase = new StringBuilder (input.length());
    boolean hadSpace = false;
    for (char c:input.toCharArray ()){
        if(Character.isSpaceChar(c)){
            hadSpace = true;
            titleCase.append (c);
            continue;
        }
        if(hadSpace){
            hadSpace = false;
            c = Character.toUpperCase(c);
            titleCase.append (c);
        }else{
            c = Character.toLowerCase(c);
            titleCase.append (c);
        }
    }
    String temp=titleCase.toString ();
    StringBuilder titleCase1 = new StringBuilder (temp.length ());
    int num=1;
    for (char c:temp.toCharArray ())
        {   if(num==1)
            c = Character.toUpperCase(c);
            titleCase1.append (c);
            num=0;
        }
        return titleCase1.toString ();
    }
}
Thomasina answered 1/10, 2019 at 17:9 Comment(1)
Here i did't use trim method anywhere beacause in my case i was getting proper trimmed string.Thomasina
E
1

It seems none of the answers format it in the actual title case: "How to Land Your Dream Job", "To Kill a Mockingbird", etc. so I've made my own method. Works best for English languages texts.

private final static Set<Character> TITLE_CASE_DELIMITERS = new HashSet<>();

  static {
    TITLE_CASE_DELIMITERS.add(' ');
    TITLE_CASE_DELIMITERS.add('.');
    TITLE_CASE_DELIMITERS.add(',');
    TITLE_CASE_DELIMITERS.add(';');
    TITLE_CASE_DELIMITERS.add('/');
    TITLE_CASE_DELIMITERS.add('-');
    TITLE_CASE_DELIMITERS.add('(');
    TITLE_CASE_DELIMITERS.add(')');
  }

  private final static Set<String> TITLE_SMALLCASED_WORDS = new HashSet<>();

  static {
    TITLE_SMALLCASED_WORDS.add("a");
    TITLE_SMALLCASED_WORDS.add("an");
    TITLE_SMALLCASED_WORDS.add("the");
    TITLE_SMALLCASED_WORDS.add("for");
    TITLE_SMALLCASED_WORDS.add("in");
    TITLE_SMALLCASED_WORDS.add("on");
    TITLE_SMALLCASED_WORDS.add("of");
    TITLE_SMALLCASED_WORDS.add("and");
    TITLE_SMALLCASED_WORDS.add("but");
    TITLE_SMALLCASED_WORDS.add("or");
    TITLE_SMALLCASED_WORDS.add("nor");
    TITLE_SMALLCASED_WORDS.add("to");
  }

  public static String toCapitalizedWord(String oneWord) {
    if (oneWord.length() < 1) {
      return oneWord.toUpperCase();
    }
    return "" + Character.toTitleCase(oneWord.charAt(0)) + oneWord.substring(1).toLowerCase();
  }

  public static String toTitledWord(String oneWord) {
    if (TITLE_SMALLCASED_WORDS.contains(oneWord.toLowerCase())) {
      return oneWord.toLowerCase();
    }
    return toCapitalizedWord(oneWord);
  }

  public static String toTitleCase(String str) {
    StringBuilder result = new StringBuilder();
    StringBuilder oneWord = new StringBuilder();

    char previousDelimiter = 'x';
    /* on start, always move to upper case */
    for (char c : str.toCharArray()) {
      if (TITLE_CASE_DELIMITERS.contains(c)) {
        if (previousDelimiter == '-' || previousDelimiter == 'x') {
          result.append(toCapitalizedWord(oneWord.toString()));
        } else {
          result.append(toTitledWord(oneWord.toString()));
        }
        oneWord.setLength(0);
        result.append(c);
        previousDelimiter = c;
      } else {
        oneWord.append(c);
      }
    }
    if (previousDelimiter == '-' || previousDelimiter == 'x') {
      result.append(toCapitalizedWord(oneWord.toString()));
    } else {
      result.append(toTitledWord(oneWord.toString()));
    }
    return result.toString();
  }

  public static void main(String[] args) {
    System.out.println(toTitleCase("one year in paris"));
    System.out.println(toTitleCase("How to Land Your Dream Job"));
  }
Extern answered 26/3, 2020 at 12:48 Comment(0)
C
1

This is the simplest solution

    static void title(String a,String b){
    String ra = Character.toString(Character.toUpperCase(a.charAt(0)));
    String rb = Character.toString(Character.toUpperCase(b.charAt(0)));
    for(int i=1;i<a.length();i++){
        ra+=a.charAt(i);
    }
    for(int i=1;i<b.length();i++){
        rb+=b.charAt(i);
    }
    System.out.println(ra+" "+rb);
Choroid answered 24/4, 2020 at 11:14 Comment(0)
P
1

Without dependency -

 public static String capitalizeFirstLetter(String s) {
    if(s.trim().length()>0){
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }
    return s;
}

public static String createTitleCase(String s) {
    if(s.trim().length()>0){
        final StringBuilder sb =  new StringBuilder();
        String[] strArr = s.split("\\s");
        for(int t =0; t < strArr.length; t++) {
            sb.append(capitalizeFirstLetter(strArr[t]));
            if(t != strArr.length-1) {
                sb.append(" ");
            }
        }

        s = sb.toString();

        sb.setLength(0);
    }
    return s;
}
Plagiarize answered 4/1, 2023 at 2:49 Comment(5)
This throws away all spacing, turning it into UpperCamelCase, not Title Case.Batrachian
Yes, just remove * in splitting string and add space between wordsPlagiarize
Your latest updated version fixes the UpperCamelCase issue. It works so long as you're OK normalizing all spaces to a single space. If the exact spacing needs to be preserved (e.g. " " should remain " " and not become " ", or "\n" should remain a newline instead of being converted to a space), then this solution couldn't be used as-is without modification.Batrachian
Yep it is too very long to reply, Validation should be done before passing values it is upto developer's work. Empty space is also a string, We cannot bound/restrict application/usage. That's why inbuilt methods are working for its need. Hence if you want to do your stuff there, you can :)Plagiarize
Sorry, I misread and thought this was splitting on runs of spaces (e.g. \\s+), not single spaces \\s. Though it does still normalize spacing, which may or may not be desired (e.g. abc\tde\tf -> Abc De F instead of Abc\tDe\tF.Batrachian
U
0

I recently ran into this problem too and unfortunately had many occurences of names beginning with Mc and Mac, I ended up using a version of scottb's code which I changed to handle these prefixes so it's here in case anyone wants to use it.

There are still edge cases which this misses but the worst thing that can happen is that a letter will be lower case when it should be capitalized.

/**
 * Get a nicely formatted representation of the name. 
 * Don't send this the whole name at once, instead send it the components.<br>
 * For example: andrew macnamara would be returned as:<br>
 * Andrew Macnamara if processed as a single string<br>
 * Andrew MacNamara if processed as 2 strings.
 * @param name
 * @return correctly formatted name
 */
public static String getNameTitleCase (String name) {
    final String ACTIONABLE_DELIMITERS = " '-/";
    StringBuilder sb = new StringBuilder();
    if (name !=null && !name.isEmpty()){                
        boolean capitaliseNext = true;
        for (char c : name.toCharArray()) {
            c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
            sb.append(c);
            capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
        }                       
        name = sb.toString();    
        if (name.startsWith("Mc") && name.length() > 2 ) {
            char c = name.charAt(2);
            if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
                sb = new StringBuilder();
                sb.append (name.substring(0,2));
                sb.append (name.substring(2,3).toUpperCase());
                sb.append (name.substring(3));
                name=sb.toString();
            }               
        } else if (name.startsWith("Mac") && name.length() > 3) {
            char c = name.charAt(3);
            if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
                sb = new StringBuilder();
                sb.append (name.substring(0,3));
                sb.append (name.substring(3,4).toUpperCase());
                sb.append (name.substring(4));
                name=sb.toString();
            }
        }
    }
    return name;    
}
Unknit answered 5/10, 2017 at 13:39 Comment(0)
S
0

Conversion to Proper Title Case :

String s= "ThiS iS SomE Text";
String[] arr = s.split(" ");
s = "";
for (String s1 : arr) {
    s += WordUtils.capitalize(s1.toLowerCase()) + " ";
}
s = s.substring(0, s.length() - 1);

Result : "This Is Some Text"

Subastral answered 20/2, 2018 at 7:6 Comment(0)
H
0

This converter transform any string containing camel case, white-spaces, digits and other characters to sanitized title case.

/**
 * Convert a string to title case in java (with tests).
 *
 * @author Sudipto Chandra
 */
public abstract class TitleCase {

    /**
     * Returns the character type. <br>
     * <br>
     * Digit = 2 <br>
     * Lower case alphabet = 0 <br>
     * Uppercase case alphabet = 1 <br>
     * All else = -1.
     *
     * @param ch
     * @return
     */
    private static int getCharType(char ch) {
        if (Character.isLowerCase(ch)) {
            return 0;
        } else if (Character.isUpperCase(ch)) {
            return 1;
        } else if (Character.isDigit(ch)) {
            return 2;
        }
        return -1;
    }

    /**
     * Converts any given string in camel or snake case to title case.
     * <br>
     * It uses the method getCharType and ignore any character that falls in
     * negative character type category. It separates two alphabets of not-equal
     * cases with a space. It accepts numbers and append it to the currently
     * running group, and puts a space at the end.
     * <br>
     * If the result is empty after the operations, original string is returned.
     *
     * @param text the text to be converted.
     * @return a title cased string
     */
    public static String titleCase(String text) {
        if (text == null || text.length() == 0) {
            return text;
        }

        char[] str = text.toCharArray();
        StringBuilder sb = new StringBuilder();

        boolean capRepeated = false;
        for (int i = 0, prev = -1, next; i < str.length; ++i, prev = next) {
            next = getCharType(str[i]);
            // trace consecutive capital cases
            if (prev == 1 && next == 1) {
                capRepeated = true;
            } else if (next != 0) {
                capRepeated = false;
            }
            // next is ignorable
            if (next == -1) {
                // System.out.printf("case 0, %d %d %s\n", prev, next, sb.toString());
                continue; // does not append anything
            }
            // prev and next are of same type
            if (prev == next) {
                sb.append(str[i]);
                // System.out.printf("case 1, %d %d %s\n", prev, next, sb.toString());
                continue;
            }
            // next is not an alphabet
            if (next == 2) {
                sb.append(str[i]);
                // System.out.printf("case 2, %d %d %s\n", prev, next, sb.toString());
                continue;
            }
            // next is an alphabet, prev was not +
            // next is uppercase and prev was lowercase
            if (prev == -1 || prev == 2 || prev == 0) {
                if (sb.length() != 0) {
                    sb.append(' ');
                }
                sb.append(Character.toUpperCase(str[i]));
                // System.out.printf("case 3, %d %d %s\n", prev, next, sb.toString());
                continue;
            }
            // next is lowercase and prev was uppercase
            if (prev == 1) {
                if (capRepeated) {
                    sb.insert(sb.length() - 1, ' ');
                    capRepeated = false;
                }
                sb.append(str[i]);
                // System.out.printf("case 4, %d %d %s\n", prev, next, sb.toString());
            }
        }
        String output = sb.toString().trim();
        output = (output.length() == 0) ? text : output;
        //return output;

        // Capitalize all words (Optional)
        String[] result = output.split(" ");
        for (int i = 0; i < result.length; ++i) {
            result[i] = result[i].charAt(0) + result[i].substring(1).toLowerCase();
        }
        output = String.join(" ", result);
        return output;
    }

    /**
     * Test method for the titleCase() function.
     */
    public static void testTitleCase() {
        System.out.println("--------------- Title Case Tests --------------------");
        String[][] samples = {
            {null, null},
            {"", ""},
            {"a", "A"},
            {"aa", "Aa"},
            {"aaa", "Aaa"},
            {"aC", "A C"},
            {"AC", "Ac"},
            {"aCa", "A Ca"},
            {"ACa", "A Ca"},
            {"aCamel", "A Camel"},
            {"anCamel", "An Camel"},
            {"CamelCase", "Camel Case"},
            {"camelCase", "Camel Case"},
            {"snake_case", "Snake Case"},
            {"toCamelCaseString", "To Camel Case String"},
            {"toCAMELCase", "To Camel Case"},
            {"_under_the_scoreCamelWith_", "Under The Score Camel With"},
            {"ABDTest", "Abd Test"},
            {"title123Case", "Title123 Case"},
            {"expect11", "Expect11"},
            {"all0verMe3", "All0 Ver Me3"},
            {"___", "___"},
            {"__a__", "A"},
            {"_A_b_c____aa", "A B C Aa"},
            {"_get$It132done", "Get It132 Done"},
            {"_122_", "122"},
            {"_no112", "No112"},
            {"Case-13title", "Case13 Title"},
            {"-no-allow-", "No Allow"},
            {"_paren-_-allow--not!", "Paren Allow Not"},
            {"Other.Allow.--False?", "Other Allow False"},
            {"$39$ldl%LK3$lk_389$klnsl-32489  3 42034 ", "39 Ldl Lk3 Lk389 Klnsl32489342034"},
            {"tHis will BE MY EXAMple", "T His Will Be My Exa Mple"},
            {"stripEvery.damn-paren- -_now", "Strip Every Damn Paren Now"},
            {"getMe", "Get Me"},
            {"whatSthePoint", "What Sthe Point"},
            {"n0pe_aLoud", "N0 Pe A Loud"},
            {"canHave SpacesThere", "Can Have Spaces There"},
            {"  why_underScore exists  ", "Why Under Score Exists"},
            {"small-to-be-seen", "Small To Be Seen"},
            {"toCAMELCase", "To Camel Case"},
            {"_under_the_scoreCamelWith_", "Under The Score Camel With"},
            {"last one onTheList", "Last One On The List"}
        };
        int pass = 0;
        for (String[] inp : samples) {
            String out = titleCase(inp[0]);
            //String out = WordUtils.capitalizeFully(inp[0]);
            System.out.printf("TEST '%s'\nWANTS '%s'\nFOUND '%s'\n", inp[0], inp[1], out);
            boolean passed = (out == null ? inp[1] == null : out.equals(inp[1]));
            pass += passed ? 1 : 0;
            System.out.println(passed ? "-- PASS --" : "!! FAIL !!");
            System.out.println();
        }
        System.out.printf("\n%d Passed, %d Failed.\n", pass, samples.length - pass);
    }

    public static void main(String[] args) {
        // run tests
        testTitleCase();
    }
}

Here are some inputs:

aCamel
TitleCase
snake_case
fromCamelCASEString
ABCTest
expect11
_paren-_-allow--not!
  why_underScore   exists  
last one onTheList 

And my outputs:

A Camel
Title Case
Snake Case
From Camel Case String
Abc Test
Expect11
Paren Allow Not
Why Under Score Exists
Last One On The List
Historian answered 25/7, 2018 at 22:43 Comment(0)
R
-1

This should work:

String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
    Character oldchar=str1.charAt(0);
    Character newchar=Character.toUpperCase(str1.charAt(0));
    strNew=strNew+str1.replace(oldchar,newchar)+" ";    
}
System.out.println(strNew);
Rosiorosita answered 29/5, 2019 at 10:29 Comment(1)
This is not a valid answer as the OP asked for builtin function. See also the comment which addresses the hidden complexity behind this, i.e. i18n.Wilmoth
M
-2

The simplest way of converting any string into a title case, is to use googles package org.apache.commons.lang.WordUtils

System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));

Will result this

This Will Be My Example

I'm not sure why its named "capitalizeFully", where in fact the function is not doing a full capital result, but anyways, thats the tool that we need.

Mitis answered 21/8, 2015 at 14:52 Comment(2)
It is named capitalizeFully because it capitalizes every word, including those that should be lower case in a title. grammar.about.com/od/tz/g/Title-Case.htmBunkmate
Apache Commons is not owned by Google. It's maintained by the Apache Software Foundation. commons.apache.orgHawthorne
A
-3

Sorry I am a beginner so my coding habit sucks!

public class TitleCase {

    String title(String sent)
    {   
        sent =sent.trim();
        sent = sent.toLowerCase();
        String[] str1=new String[sent.length()];
        for(int k=0;k<=str1.length-1;k++){
            str1[k]=sent.charAt(k)+"";
    }

        for(int i=0;i<=sent.length()-1;i++){
            if(i==0){
                String s= sent.charAt(i)+"";
                str1[i]=s.toUpperCase();
                }
            if(str1[i].equals(" ")){
                String s= sent.charAt(i+1)+"";
                str1[i+1]=s.toUpperCase();
                }

            System.out.print(str1[i]);
            }

        return "";
        }

    public static void main(String[] args) {
        TitleCase a = new TitleCase();
        System.out.println(a.title("   enter your Statement!"));
    }
}
Allodium answered 14/8, 2014 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.