How to capitalize the first character of each word in a string
Asked Answered
S

52

472

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

  • jon skeet -> Jon Skeet
  • miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
  • old mcdonald -> Old Mcdonald*

*(Old McDonald would be find too, but I don't expect it to be THAT smart.)

A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.

Stalk answered 12/12, 2009 at 8:25 Comment(7)
What about old mcdonald? Should that become Old McDonald?Outspeak
I don't expect the function to be that smart. (Although if you have one I'd be happy to see it.) Just Up the first letter after white space, but ignore the rest.Stalk
releated: #1150355Briscoe
You wouldn't be able to find an algorithm that properly handles name capitalization after the fact anyway ... as long as there are pairs of names, either of which may be correct for a given person, like MacDonald and Macdonald, the function would have no way of knowing which was correct. It's better to do what you did, although you'll still get some names wrong (like von Neumann).Lacerate
Try Burger King ...Eventide
Also related: #22230806Olecranon
Good read: w3.org/International/questions/qa-personal-namesOlecranon
C
798

WordUtils.capitalize(str) (from apache commons-text)

(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)

Chokebore answered 12/12, 2009 at 8:30 Comment(18)
I think you mean WordUtils.capitalize(str). See API for details.Monies
yeah. StringUtils also has it, but for one-word strings. Thanks.Chokebore
Keeping my philosophy of always voting up answers that refer to the commons libraries.Wivina
A common library is exactly what I was asking for: debugging (hopefully) done. Still would love to see a function that doesn't require a download separate from the JDK, but this is everything else I was looking for. Thank you!Stalk
To change the non-first letter to the words to lowercase, use capitalizeFully(str).Jobe
I wonder why this answer got so many upvotes. According to documentation WordUtils.capitalize(str) "Capitalizes all the whitespace separated words in a String." So, in order to accomplish Willfulwizard's task capitalize(String str, char[] delimiters) method should be used where all possible delimiters must be specified. I would consider that inconvenient.Select
well, capitalize(..) will cover his case. The only exception would be if "o'brian" is specified - then B won't be capitalized. In that case you can use the extra char[] delimiters, indeedChokebore
and I guess it got so many upvotes because it answers the title. People usually look for how to capitalize words and find this usefulChokebore
Is this solution really correct? it isn't in my opinion! If you want to capitalize "LAMborghini", you want "Lamborghini" in the end. So WordUtils.capitalizeFully(str) is the solution.Flanagan
@BasZero it is the right answer to the question asked. I will include the Fully version as a comment.Chokebore
I think these methods in this library should also take a Locale parameter.Sestet
when i try using WordUtils and hover over it, there is no import optionPhylloid
In this case I'd prefer capitalizeFully(String, char...)Tetter
Unfortunately, the discussed functions of the common library do not support surrogate pairs, which get more and more common.Frith
Now this method is moved from commons-lang to commons-text and yes it support surrogate pairs as well.Puny
Just a note, WordUtils is now deprecated, and part of the Apache Commons Text library - commons.apache.org/proper/commons-textCarpet
The capitalize doesn't properly capitalize names with ' in it: capitalize("rick o'shea") returns Rick O'shea instead of Rick O'Shea.Jeanninejeans
@GuillaumeF you can specify the words separators: String fullyCapitalized = WordUtils.capitalizeFully("rick o'shea", ' ', '\'');Forked
P
233

If you're only worried about the first letter of the first word being capitalized:

private String capitalize(final String line) {
   return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
Pyx answered 22/6, 2012 at 2:48 Comment(8)
this only changes the first letter of the first wordLianne
Indeed, this was my intention.Pyx
@nbolton - But it explicitly ignores the intent of the question, and fails for the very cases given in that example - and it adds little or nothing to the answers previously given!Overstrain
This piece of code is not crash-safe! Imagine line being null or having a length of < 2.Bierman
still, return Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase()Aged
@Bierman substring(1) is fine for single character strings.Placoid
if string have only one character it is okey... but if it contains space at the start or it is empty java throw exception... you should firstly control is it empty? with trim().isEmpty() then you should before use this function, use trim() at the string because space can cause exceptionLaudation
To pick a nit, shouldn't it be static?Wauters
G
87

The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.

public static String capitalizeString(String string) {
  char[] chars = string.toLowerCase().toCharArray();
  boolean found = false;
  for (int i = 0; i < chars.length; i++) {
    if (!found && Character.isLetter(chars[i])) {
      chars[i] = Character.toUpperCase(chars[i]);
      found = true;
    } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
      found = false;
    }
  }
  return String.valueOf(chars);
}
Greensand answered 12/12, 2009 at 8:53 Comment(8)
I would improve and simplify the loop conditions: if(Character.isLetter(chars[i])) { if(!found) { chars[i] = Character.toUpperCase(chars[i]); } found = true; } else { found = false; }.Select
@bancer, with your example you can't control which characters won't be followed by an uppercase letter.Greensand
@TrueSoft, I do not understand you. Why do you need to control what characters follows after uppercase letter? As I understood it is important that the preceding character would not be a letter and my example ensures that. Just replace your if-else-if block with my if-else block and run a test.Select
@TrueSoft, for clarity I would rename found to previousCharIsLetter.Select
@bancer, In my example, for "my@email" the result is "My@email". In your case, the e after @ would be uppercase. So I can decide when I should make a letter uppercase: after a whitespace, or . and ' characters.Greensand
@TomHawtin please take a look at mine answer (check if it works), i've started to handle surrogate pairs after reading your comment :) never heard of that before...Philippopolis
I like having answers that don't use the commons library, because every once in a while you can't use it.Wentletrap
Instead of adding all the characters manually you can simply use else if (!(Character.isDigit(chars[i]) || Character.isLetter(chars[i]))) { found = false; }Grimonia
T
48

Try this very simple way

example givenString="ram is good boy"

public static String toTitleCase(String givenString) {
    String[] arr = givenString.split(" ");
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < arr.length; i++) {
        sb.append(Character.toUpperCase(arr[i].charAt(0)))
            .append(arr[i].substring(1)).append(" ");
    }          
    return sb.toString().trim();
}  

Output will be: Ram Is Good Boy

Toothpaste answered 13/2, 2013 at 7:56 Comment(4)
this code caused our server to crash:java.lang.StringIndexOutOfBoundsException: String index out of range: 0Lianne
@Chrizzz so do not commit code you did not test... If you provide an empty string, it does crash. Your fault, not Neelam's.Literator
If there is a space at the end then it is crashing then I added trim() first and split string with space.It worked perfectlyBearded
In case someone is looking for its Kotlin version, here is it: https://mcmap.net/q/75260/-how-to-capitalize-the-first-character-of-each-word-in-a-stringOuch
S
21

I made a solution in Java 8 that is IMHO more readable.

public String firstLetterCapitalWithSingleSpace(final String words) {
    return Stream.of(words.trim().split("\\s"))
    .filter(word -> word.length() > 0)
    .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
    .collect(Collectors.joining(" "));
}

The Gist for this solution can be found here: https://gist.github.com/Hylke1982/166a792313c5e2df9d31

Sloe answered 17/2, 2015 at 11:53 Comment(0)
U
17
String toBeCapped = "i want this sentence capitalized";

String[] tokens = toBeCapped.split("\\s");
toBeCapped = "";

for(int i = 0; i < tokens.length; i++){
    char capLetter = Character.toUpperCase(tokens[i].charAt(0));
    toBeCapped +=  " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();
Unideaed answered 10/8, 2011 at 14:10 Comment(2)
Hmmm, I think the second line in the for loop should read: toBeCapped += " " + capLetter + tokens[i].substring(1, tokens[i].length());Etalon
But this solution will add a whitespace at the starting. So you may need to do left trim.Yahrzeit
P
16

I've written a small Class to capitalize all the words in a String.

Optional multiple delimiters, each one with its behavior (capitalize before, after, or both, to handle cases like O'Brian);

Optional Locale;

Don't breaks with Surrogate Pairs.

LIVE DEMO

Output:

====================================
 SIMPLE USAGE
====================================
Source: cApItAlIzE this string after WHITE SPACES
Output: Capitalize This String After White Spaces

====================================
 SINGLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string ONLY before'and''after'''APEX
Output: Capitalize this string only beforE'AnD''AfteR'''Apex

====================================
 MULTIPLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)
Output: Capitalize This String After Spaces, BeforE'apex, And #After And BeforE# Number Sign (#)

====================================
 SIMPLE USAGE WITH CUSTOM LOCALE
====================================
Source: Uniforming the first and last vowels (different kind of 'i's) of the Turkish word D[İ]YARBAK[I]R (DİYARBAKIR) 
Output: Uniforming The First And Last Vowels (different Kind Of 'i's) Of The Turkish Word D[i]yarbak[i]r (diyarbakir) 

====================================
 SIMPLE USAGE WITH A SURROGATE PAIR 
====================================
Source: ab 𐐂c de à
Output: Ab 𐐪c De À

Note: first letter will always be capitalized (edit the source if you don't want that).

Please share your comments and help me to found bugs or to improve the code...

Code:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class WordsCapitalizer {

    public static String capitalizeEveryWord(String source) {
        return capitalizeEveryWord(source,null,null);
    }

    public static String capitalizeEveryWord(String source, Locale locale) {
        return capitalizeEveryWord(source,null,locale);
    }

    public static String capitalizeEveryWord(String source, List<Delimiter> delimiters, Locale locale) {
        char[] chars; 

        if (delimiters == null || delimiters.size() == 0)
            delimiters = getDefaultDelimiters();                

        // If Locale specified, i18n toLowerCase is executed, to handle specific behaviors (eg. Turkish dotted and dotless 'i')
        if (locale!=null)
            chars = source.toLowerCase(locale).toCharArray();
        else 
            chars = source.toLowerCase().toCharArray();

        // First charachter ALWAYS capitalized, if it is a Letter.
        if (chars.length>0 && Character.isLetter(chars[0]) && !isSurrogate(chars[0])){
            chars[0] = Character.toUpperCase(chars[0]);
        }

        for (int i = 0; i < chars.length; i++) {
            if (!isSurrogate(chars[i]) && !Character.isLetter(chars[i])) {
                // Current char is not a Letter; gonna check if it is a delimitrer.
                for (Delimiter delimiter : delimiters){
                    if (delimiter.getDelimiter()==chars[i]){
                        // Delimiter found, applying rules...                       
                        if (delimiter.capitalizeBefore() && i>0 
                            && Character.isLetter(chars[i-1]) && !isSurrogate(chars[i-1]))
                        {   // previous character is a Letter and I have to capitalize it
                            chars[i-1] = Character.toUpperCase(chars[i-1]);
                        }
                        if (delimiter.capitalizeAfter() && i<chars.length-1 
                            && Character.isLetter(chars[i+1]) && !isSurrogate(chars[i+1]))
                        {   // next character is a Letter and I have to capitalize it
                            chars[i+1] = Character.toUpperCase(chars[i+1]);
                        }
                        break;
                    }
                } 
            }
        }
        return String.valueOf(chars);
    }


    private static boolean isSurrogate(char chr){
        // Check if the current character is part of an UTF-16 Surrogate Pair.  
        // Note: not validating the pair, just used to bypass (any found part of) it.
        return (Character.isHighSurrogate(chr) || Character.isLowSurrogate(chr));
    }       

    private static List<Delimiter> getDefaultDelimiters(){
        // If no delimiter specified, "Capitalize after space" rule is set by default. 
        List<Delimiter> delimiters = new ArrayList<Delimiter>();
        delimiters.add(new Delimiter(Behavior.CAPITALIZE_AFTER_MARKER, ' '));
        return delimiters;
    } 

    public static class Delimiter {
        private Behavior behavior;
        private char delimiter;

        public Delimiter(Behavior behavior, char delimiter) {
            super();
            this.behavior = behavior;
            this.delimiter = delimiter;
        }

        public boolean capitalizeBefore(){
            return (behavior.equals(Behavior.CAPITALIZE_BEFORE_MARKER)
                    || behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
        }

        public boolean capitalizeAfter(){
            return (behavior.equals(Behavior.CAPITALIZE_AFTER_MARKER)
                    || behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
        }

        public char getDelimiter() {
            return delimiter;
        }
    }

    public static enum Behavior {
        CAPITALIZE_AFTER_MARKER(0),
        CAPITALIZE_BEFORE_MARKER(1),
        CAPITALIZE_BEFORE_AND_AFTER_MARKER(2);                      

        private int value;          

        private Behavior(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }           
    } 
Philippopolis answered 30/11, 2012 at 16:55 Comment(0)
C
10

Using org.apache.commons.lang.StringUtils makes it very simple.

capitalizeStr = StringUtils.capitalize(str);
Canister answered 11/6, 2015 at 10:48 Comment(2)
@Ash StringUtils.capitalise(str) is deprecated. See: commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/…Turnstile
This only capitalises the first char of the string not the first char of each word in the string. WordUtils is only deprecated because it has moved from commons lang to commons text commons.apache.org/proper/commons-text/javadocs/api-release/org/…Swam
L
10

From Java 9+

you can use Matcher::replaceAll like this :

public static void upperCaseAllFirstCharacter(String text) {
    String regex = "\\b(.)(.*?)\\b";
    String result = Pattern.compile(regex).matcher(text).replaceAll(
            matche -> matche.group(1).toUpperCase() + matche.group(2)
    );

    System.out.println(result);
}

Example :

upperCaseAllFirstCharacter("hello this is Just a test");

Outputs

Hello This Is Just A Test
Lacielacing answered 26/4, 2018 at 14:25 Comment(1)
Good answer, which benefits from not introducing any non-standard dependencies. Just one minor niggle: the method you use here is actually Matcher::replaceAll; not String::replaceAllCyb
P
7

With this simple code:

String example="hello";

example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());

System.out.println(example);

Result: Hello

Postman answered 25/5, 2013 at 21:58 Comment(1)
what about HELLO it returns HELLO but expected Hello so you shall use toLowerCase() in second SubStringKero
F
6

I'm using the following function. I think it is faster in performance.

public static String capitalize(String text){
    String c = (text != null)? text.trim() : "";
    String[] words = c.split(" ");
    String result = "";
    for(String w : words){
        result += (w.length() > 1? w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1, w.length()).toLowerCase(Locale.US) : w) + " ";
    }
    return result.trim();
}
Fagen answered 7/10, 2016 at 20:55 Comment(2)
Always use StringBuilder when you concatenate rather than +=Virginity
Why do you think it is faster?Chasidychasing
C
6

1. Java 8 Streams

public static String capitalizeAll(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    return Arrays.stream(str.split("\\s+"))
            .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
            .collect(Collectors.joining(" "));
}

Examples:

System.out.println(capitalizeAll("jon skeet")); // Jon Skeet
System.out.println(capitalizeAll("miles o'Brien")); // Miles O'Brien
System.out.println(capitalizeAll("old mcdonald")); // Old Mcdonald
System.out.println(capitalizeAll(null)); // null

For foo bAR to Foo Bar, replace the map() method with the following:

.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())

2. String.replaceAll() (Java 9+)

ublic static String capitalizeAll(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    return Pattern.compile("\\b(.)(.*?)\\b")
            .matcher(str)
            .replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
}

Examples:

System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
System.out.println(capitalizeAll("i am atta")); // I Am Atta
System.out.println(capitalizeAll(null)); // null

3. Apache Commons Text

System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
System.out.println(WordUtils.capitalize(null)); // null

For titlecase:

System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!

For details, checkout this tutorial.

Clemons answered 14/9, 2019 at 16:47 Comment(0)
B
4

Use the Split method to split your string into words, then use the built in string functions to capitalize each word, then append together.

Pseudo-code (ish)

string = "the sentence you want to apply caps to";
words = string.split(" ") 
string = ""
for(String w: words)

//This line is an easy way to capitalize a word
    word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())

    string += word

In the end string looks something like "The Sentence You Want To Apply Caps To"

Blurt answered 24/7, 2012 at 23:59 Comment(0)
G
4

This might be useful if you need to capitalize titles. It capitalizes each substring delimited by " ", except for specified strings such as "a" or "the". I haven't ran it yet because it's late, should be fine though. Uses Apache Commons StringUtils.join() at one point. You can substitute it with a simple loop if you wish.

private static String capitalize(String string) {
    if (string == null) return null;
    String[] wordArray = string.split(" "); // Split string to analyze word by word.
    int i = 0;
lowercase:
    for (String word : wordArray) {
        if (word != wordArray[0]) { // First word always in capital
            String [] lowercaseWords = {"a", "an", "as", "and", "although", "at", "because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"};
            for (String word2 : lowercaseWords) {
                if (word.equals(word2)) {
                    wordArray[i] = word;
                    i++;
                    continue lowercase;
                }
            }
        }
        char[] characterArray = word.toCharArray();
        characterArray[0] = Character.toTitleCase(characterArray[0]);
        wordArray[i] = new String(characterArray);
        i++;
    }
    return StringUtils.join(wordArray, " "); // Re-join string
}
Gipps answered 2/10, 2012 at 19:45 Comment(1)
Breaks if string has double spaces in it, which is dumb for input, but FYI.Superhuman
L
4
public static String toTitleCase(String word){
    return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}

public static void main(String[] args){
    String phrase = "this is to be title cased";
    String[] splitPhrase = phrase.split(" ");
    String result = "";

    for(String word: splitPhrase){
        result += toTitleCase(word) + " ";
    }
    System.out.println(result.trim());
}
Leblanc answered 15/4, 2018 at 21:40 Comment(2)
Welcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.Yama
Simplest solution by far and avoids using external libsMic
S
4

Here we go for perfect first char capitalization of word

public static void main(String[] args) {
    String input ="my name is ranjan";
    String[] inputArr = input.split(" ");

    for(String word : inputArr) {
        System.out.println(word.substring(0, 1).toUpperCase()+word.substring(1,word.length()));
    }   
}

}

//Output : My Name Is Ranjan

Standoffish answered 6/5, 2019 at 4:49 Comment(3)
You can add following part and get the exact capitalized word. String input ="my name is ranjan"; String[] inputArr = input.split(" "); String capitalizedWord = ""; for(String word : inputArr) { capitalizedWord=capitalizedWord+(word.substring(0, 1).toUpperCase()+word.substring(1,word.length()))+" "; } System.out.println(capitalizedWord.trim());Navy
Hi @Ranjan, your code will print the output like below; My Name Is RanjanMcclelland
To print the output as, //Output : My Name Is Ranjan There needs to do slight modification like this; public static void main(String[] args) { String input = "my name is ranjan"; String[] inputArr = input.split(" "); for (String word : inputArr) { System.out.print(word.substring(0, 1).toUpperCase() + word.substring(1, word.length()) + " "); } } }Mcclelland
R
3
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   

System.out.println("Enter the sentence : ");

try
{
    String str = br.readLine();
    char[] str1 = new char[str.length()];

    for(int i=0; i<str.length(); i++)
    {
        str1[i] = Character.toLowerCase(str.charAt(i));
    }

    str1[0] = Character.toUpperCase(str1[0]);
    for(int i=0;i<str.length();i++)
    {
        if(str1[i] == ' ')
        {                   
            str1[i+1] =  Character.toUpperCase(str1[i+1]);
        }
        System.out.print(str1[i]);
    }
}
catch(Exception e)
{
    System.err.println("Error: " + e.getMessage());
}
Raymonraymond answered 8/8, 2011 at 8:3 Comment(1)
This is the most simple, basic and best answer for a novice like me!Gwenngwenneth
C
3

Here is a simple function

public static String capEachWord(String source){
    String result = "";
    String[] splitString = source.split(" ");
    for(String target : splitString){
        result += Character.toUpperCase(target.charAt(0))
                + target.substring(1) + " ";
    }
    return result.trim();
}
Cynic answered 20/3, 2013 at 12:59 Comment(1)
Don't use string-concation for creating long strings, it's painfully slow: #15178487Junk
B
3

Use:

    String text = "jon skeet, miles o'brien, old mcdonald";

    Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");
    Matcher matcher = pattern.matcher(text);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
    }
    String capitalized = matcher.appendTail(buffer).toString();
    System.out.println(capitalized);
Bullshit answered 26/11, 2013 at 22:23 Comment(1)
Works perfectly with toLowerCase -> "Matcher matcher = pattern.matcher(text.toLowerCase());" (For entry text like "JOHN DOE")Mil
U
3

There are many way to convert the first letter of the first word being capitalized. I have an idea. It's very simple:

public String capitalize(String str){

     /* The first thing we do is remove whitespace from string */
     String c = str.replaceAll("\\s+", " ");
     String s = c.trim();
     String l = "";

     for(int i = 0; i < s.length(); i++){
          if(i == 0){                              /* Uppercase the first letter in strings */
              l += s.toUpperCase().charAt(i);
              i++;                                 /* To i = i + 1 because we don't need to add               
                                                    value i = 0 into string l */
          }

          l += s.charAt(i);

          if(s.charAt(i) == 32){                   /* If we meet whitespace (32 in ASCII Code is whitespace) */
              l += s.toUpperCase().charAt(i+1);    /* Uppercase the letter after whitespace */
              i++;                                 /* Yo i = i + 1 because we don't need to add
                                                   value whitespace into string l */
          }        
     }
     return l;
}
Unaccustomed answered 28/12, 2014 at 4:22 Comment(1)
Thanks for trying to add an answer. This is a reasonable idea, but note that there are basic functions that do this already, and code that does this similarly to what you provided, and the accepted answers already outline all of them very clearly.Overstrain
A
3

I decided to add one more solution for capitalizing words in a string:

  • words are defined here as adjacent letter-or-digit characters;
  • surrogate pairs are provided as well;
  • the code has been optimized for performance; and
  • it is still compact.

Function:

public static String capitalize(String string) {
  final int sl = string.length();
  final StringBuilder sb = new StringBuilder(sl);
  boolean lod = false;
  for(int s = 0; s < sl; s++) {
    final int cp = string.codePointAt(s);
    sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
    lod = Character.isLetterOrDigit(cp);
    if(!Character.isBmpCodePoint(cp)) s++;
  }
  return sb.toString();
}

Example call:

System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs: 𐐪𐐪."));

Result:

An À La Carte String. Surrogate Pairs: 𐐂𐐪.
Ammoniac answered 2/3, 2017 at 14:9 Comment(0)
P
2
  package com.test;

 /**
   * @author Prasanth Pillai
   * @date 01-Feb-2012
   * @description : Below is the test class details
   * 
   * inputs a String from a user. Expect the String to contain spaces and    alphanumeric     characters only.
   * capitalizes all first letters of the words in the given String.
   * preserves all other characters (including spaces) in the String.
   * displays the result to the user.
   * 
   * Approach : I have followed a simple approach. However there are many string    utilities available 
   * for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
   *
   */
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;

  public class Test {

public static void main(String[] args) throws IOException{
    System.out.println("Input String :\n");
    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);
    String inputString = in.readLine();
    int length = inputString.length();
    StringBuffer newStr = new StringBuffer(0);
    int i = 0;
    int k = 0;
    /* This is a simple approach
     * step 1: scan through the input string
     * step 2: capitalize the first letter of each word in string
     * The integer k, is used as a value to determine whether the 
     * letter is the first letter in each word in the string.
     */

    while( i < length){
        if (Character.isLetter(inputString.charAt(i))){
            if ( k == 0){
            newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
            k = 2;
            }//this else loop is to avoid repeatation of the first letter in output string 
            else {
            newStr = newStr.append(inputString.charAt(i));
            }
        } // for the letters which are not first letter, simply append to the output string. 
        else {
            newStr = newStr.append(inputString.charAt(i));
            k=0;
        }
        i+=1;           
    }
    System.out.println("new String ->"+newStr);
    }
}
Pasteup answered 1/2, 2012 at 12:30 Comment(0)
O
2

This is just another way of doing it:

private String capitalize(String line)
{
    StringTokenizer token =new StringTokenizer(line);
    String CapLine="";
    while(token.hasMoreTokens())
    {
        String tok = token.nextToken().toString();
        CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";        
    }
    return CapLine.substring(0,CapLine.length()-1);
}
Ortiz answered 29/1, 2014 at 6:38 Comment(0)
H
2

Reusable method for intiCap:

    public class YarlagaddaSireeshTest{

    public static void main(String[] args) {
        String FinalStringIs = "";
        String testNames = "sireesh yarlagadda test";
        String[] name = testNames.split("\\s");

        for(String nameIs :name){
            FinalStringIs += getIntiCapString(nameIs) + ",";
        }
        System.out.println("Final Result "+ FinalStringIs);
    }

    public static String getIntiCapString(String param) {
        if(param != null && param.length()>0){          
            char[] charArray = param.toCharArray(); 
            charArray[0] = Character.toUpperCase(charArray[0]); 
            return new String(charArray); 
        }
        else {
            return "";
        }
    }
}
Hubie answered 13/6, 2014 at 20:9 Comment(0)
L
2

Here is my solution.

I ran across this problem tonight and decided to search it. I found an answer by Neelam Singh that was almost there, so I decided to fix the issue (broke on empty strings) and caused a system crash.

The method you are looking for is named capString(String s) below. It turns "It's only 5am here" into "It's Only 5am Here".

The code is pretty well commented, so enjoy.

package com.lincolnwdaniel.interactivestory.model;

    public class StringS {

    /**
     * @param s is a string of any length, ideally only one word
     * @return a capitalized string.
     * only the first letter of the string is made to uppercase
     */
    public static String capSingleWord(String s) {
        if(s.isEmpty() || s.length()<2) {
            return Character.toUpperCase(s.charAt(0))+"";
        } 
        else {
            return Character.toUpperCase(s.charAt(0)) + s.substring(1);
        }
    }

    /**
     *
     * @param s is a string of any length
     * @return a title cased string.
     * All first letter of each word is made to uppercase
     */
    public static String capString(String s) {
        // Check if the string is empty, if it is, return it immediately
        if(s.isEmpty()){
            return s;
        }

        // Split string on space and create array of words
        String[] arr = s.split(" ");
        // Create a string buffer to hold the new capitalized string
        StringBuffer sb = new StringBuffer();

        // Check if the array is empty (would be caused by the passage of s as an empty string [i.g "" or " "],
        // If it is, return the original string immediately
        if( arr.length < 1 ){
            return s;
        }

        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                    .append(arr[i].substring(1)).append(" ");
        }
        return sb.toString().trim();
    }
}
Lauer answered 8/1, 2015 at 10:3 Comment(0)
B
1

For those of you using Velocity in your MVC, you can use the capitalizeFirstLetter() method from the StringUtils class.

Banzai answered 14/9, 2011 at 0:26 Comment(0)
D
1
String s="hi dude i                                 want apple";
    s = s.replaceAll("\\s+"," ");
    String[] split = s.split(" ");
    s="";
    for (int i = 0; i < split.length; i++) {
        split[i]=Character.toUpperCase(split[i].charAt(0))+split[i].substring(1);
        s+=split[i]+" ";
        System.out.println(split[i]);
    }
    System.out.println(s);
Dissident answered 2/1, 2013 at 12:8 Comment(0)
S
1

The short and precise way is as follows:

String name = "test";

name = (name.length() != 0) ?name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)): name;
--------------------
Output
--------------------
Test
T 
empty
--------------------

It works without error if you try and change the name value to the three of values. Error free.

Streeter answered 6/5, 2014 at 13:16 Comment(1)
what if it's more than one wordStadiometer
N
1

This one works for the surname case...

With different types of separators, and it keeps the same separator:

  • jean-frederic --> Jean-Frederic

  • jean frederic --> Jean Frederic

The code works with the GWT client side.

public static String capitalize (String givenString) {
    String Separateur = " ,.-;";
    StringBuffer sb = new StringBuffer(); 
    boolean ToCap = true;
    for (int i = 0; i < givenString.length(); i++) {
        if (ToCap)              
            sb.append(Character.toUpperCase(givenString.charAt(i)));
        else
            sb.append(Character.toLowerCase(givenString.charAt(i)));

        if (Separateur.indexOf(givenString.charAt(i)) >=0) 
            ToCap = true;
        else
            ToCap = false;
    }          
    return sb.toString().trim();
}  
Nystrom answered 28/5, 2014 at 16:54 Comment(0)
S
1
package corejava.string.intern;

import java.io.DataInputStream;

import java.util.ArrayList;

/*
 * wap to accept only 3 sentences and convert first character of each word into upper case
 */

public class Accept3Lines_FirstCharUppercase {

    static String line;
    static String words[];
    static ArrayList<String> list=new ArrayList<String>();

    /**
     * @param args
     */
    public static void main(String[] args) throws java.lang.Exception{

        DataInputStream read=new DataInputStream(System.in);
        System.out.println("Enter only three sentences");
        int i=0;
        while((line=read.readLine())!=null){
            method(line);       //main logic of the code
            if((i++)==2){
                break;
            }
        }
        display();
        System.out.println("\n End of the program");

    }

    /*
     * this will display all the elements in an array
     */
    public static void display(){
        for(String display:list){
            System.out.println(display);
        }
    }

    /*
     * this divide the line of string into words 
     * and first char of the each word is converted to upper case
     * and to an array list
     */
    public static void method(String lineParam){
        words=line.split("\\s");
        for(String s:words){
            String result=s.substring(0,1).toUpperCase()+s.substring(1);
            list.add(result);
        }
    }

}
Saskatoon answered 25/7, 2014 at 6:56 Comment(0)
T
1

If you prefer Guava...

String myString = ...;

String capWords = Joiner.on(' ').join(Iterables.transform(Splitter.on(' ').omitEmptyStrings().split(myString), new Function<String, String>() {
    public String apply(String input) {
        return Character.toUpperCase(input.charAt(0)) + input.substring(1);
    }
}));
Terbecki answered 3/11, 2014 at 23:27 Comment(0)
C
1

Try this:

 private String capitalizer(String word){

        String[] words = word.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());
            }
        }
        return  sb.toString();
    }
Cynthy answered 10/6, 2015 at 9:31 Comment(0)
L
1
String toUpperCaseFirstLetterOnly(String str) {
    String[] words = str.split(" ");
    StringBuilder ret = new StringBuilder();
    for(int i = 0; i < words.length; i++) {
        ret.append(Character.toUpperCase(words[i].charAt(0)));
        ret.append(words[i].substring(1));
        if(i < words.length - 1) {
            ret.append(' ');
        }
    }
    return ret.toString();
}
Lyingin answered 11/7, 2017 at 14:51 Comment(0)
O
1

Here is the Kotlin version of the same problem:

fun capitalizeFirstLetterOfEveryWord(text: String): String
{
    if (text.isEmpty() || text.isBlank())
    {
        return ""
    }

    if (text.length == 1)
    {
        return Character.toUpperCase(text[0]).toString()
    }

    val textArray = text.split(" ")
    val stringBuilder = StringBuilder()

    for ((index, item) in textArray.withIndex())
    {
        // If item is empty string, continue to next item
        if (item.isEmpty())
        {
            continue
        }

        stringBuilder
            .append(Character.toUpperCase(item[0]))

        // If the item has only one character then continue to next item because we have already capitalized it.
        if (item.length == 1)
        {
            continue
        }

        for (i in 1 until item.length)
        {
            stringBuilder
                .append(Character.toLowerCase(item[i]))
        }

        if (index < textArray.lastIndex)
        {
            stringBuilder
                .append(" ")
        }
    }

    return stringBuilder.toString()
}
Ouch answered 28/3, 2019 at 4:28 Comment(0)
C
0

I had a requirement to make a generic toString(Object obj) helper class function, where I had to convert the fieldnames into methodnames - getXXX() of the passed Object.

Here is the code

/**
 * @author DPARASOU
 * Utility method to replace the first char of a string with uppercase but leave other chars as it is.
 * ToString() 
 * @param inStr - String
 * @return String
 */
public static String firstCaps(String inStr)
{
    if (inStr != null && inStr.length() > 0)
    {
        char[] outStr = inStr.toCharArray();
        outStr[0] = Character.toUpperCase(outStr[0]);
        return String.valueOf(outStr);
    }
    else
        return inStr;
}

And my toString() utility is like this

public static String getToString(Object obj)
{
    StringBuilder toString = new StringBuilder();
    toString.append(obj.getClass().getSimpleName());
    toString.append("[");
    for(Field f : obj.getClass().getDeclaredFields())
    {
        toString.append(f.getName());
        toString.append("=");
        try{
            //toString.append(f.get(obj)); //access privilege issue
            toString.append(invokeGetter(obj, firstCaps(f.getName()), "get"));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        toString.append(", ");        
    }
    toString.setCharAt(toString.length()-2, ']');
    return toString.toString();
}
Charles answered 1/4, 2015 at 11:25 Comment(0)
P
0
Simple answer by program:


public class StringCamelCase {
    public static void main(String[] args) {
        String[] articles = {"the ", "a ", "one ", "some ", "any "};
        String[] result = new String[articles.length];
        int i = 0;
        for (String string : articles) {
            result[i++] = toUpercaseForstChar(string);
        }

        for (String string : result) {
            System.out.println(string);
        }
    }
    public static String toUpercaseForstChar(String string){
        return new String(new char[]{string.charAt(0)}).toUpperCase() + string.substring(1,string.length());
    }
}
Piecrust answered 8/5, 2016 at 8:45 Comment(0)
L
0

The most basic and easiest way to understand (I think):

import java.util.Scanner;

public class ToUpperCase {
    static Scanner kb = new Scanner(System.in);

    public static String capitalize(String str){
        /* Changes 1st letter of every word 
           in a string to upper case
         */
        String[] ss = str.split(" ");
        StringBuilder[] sb = new StringBuilder[ss.length];
        StringBuilder capped = new StringBuilder("");
        str = "";

        // Capitalise letters
        for (int i = 0; i < ss.length; i++){
            sb[i] = new StringBuilder(ss[i]); // Construct and assign
            str += Character.toUpperCase(ss[i].charAt(0)); // Only caps
            //======================================================//

            // Replace 1st letters with cap letters
            sb[i].setCharAt(0, str.charAt(i)); 
            capped.append(sb[i].toString() + " ");  // Formatting
        }
        return capped.toString();
    }

    public static void main(String[] args){
        System.out.println(capitalize(kb.nextLine()));
    }
}
Lumenhour answered 7/6, 2016 at 23:42 Comment(0)
J
0

Since nobody used regexp's let's do it with regexp's. This solution is for fun. :) (update: actually I just discovered that there is an answer with regexps, anyway I would like to leave this answer in place since it is better looking :) ):

public class Capitol 
{
    public static String now(String str)
    {
        StringBuffer b = new StringBuffer();
        Pattern p = Pattern.compile("\\b(\\w){1}");
        Matcher m = p.matcher(str);
        while (m.find())
        {
            String s = m.group(1);
            m.appendReplacement(b, s.toUpperCase());
        }
        m.appendTail(b);
        return b.toString();
    }
}

Usage

Capitol.now("ab cd"));
Capitol.now("winnie the Pooh"));
Capitol.now("please talk loudly!"));
Capitol.now("miles o'Brien"));
Jemma answered 22/6, 2017 at 10:4 Comment(1)
you need to rename your class from Capitol to Capital :)Trev
A
0

I use wordUppercase(String s) from the Raindrop-Library. Because this is my library, here the single method:

 /**
  * Set set first letter from every word uppercase.
  *
  * @param s - The String wich you want to convert.
  * @return The string where is the first letter of every word uppercase.
  */
 public static String wordUppercase(String s){
   String[] words = s.split(" ");
   for (int i = 0; i < words.length; i++) words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
   return String.join(" ", words);
 }

Hope it helps :)

Ablaut answered 3/10, 2017 at 12:43 Comment(0)
S
0
public void capitaliseFirstLetterOfEachWord()
{
    String value="this will capitalise first character of each word of this string";
    String[] wordSplit=value.split(" ");
    StringBuilder sb=new StringBuilder();

    for (int i=0;i<wordSplit.length;i++){

        sb.append(wordSplit[i].substring(0,1).toUpperCase().
                concat(wordSplit[i].substring(1)).concat(" "));
    }
    System.out.println(sb);
}
Subjection answered 7/10, 2017 at 18:40 Comment(0)
A
0
    s.toLowerCase().trim();
    result += Character.toUpperCase(s.charAt(0));
    result += s.substring(1, s.indexOf(" ") + 1);
    s = s.substring(s.indexOf(" ") + 1);

    do {
        if (s.contains(" ")) {
            result += " ";
            result += Character.toUpperCase(s.charAt(0));
            result += s.substring(1, s.indexOf(" "));
            s = s.substring(s.indexOf(" ") + 1);
        } else {
            result += " ";
            result += Character.toUpperCase(s.charAt(0));
            result += s.substring(1);
            break;
        }
    } while (true);
    System.out.println(result);
Astray answered 13/3, 2018 at 5:43 Comment(0)
E
0
String text="hello";
StringBuffer sb=new StringBuffer();
char[] ch=text.toCharArray();
for(int i=0;i<ch.length;i++){
    if(i==0){
        sb.append(Character.toUpperCase(ch[i]));
    }
    else{
    sb.append(ch[i]);
    }
}


text=sb.toString();
System.out.println(text);
}
Exorcise answered 25/3, 2018 at 14:30 Comment(0)
L
0

Here is RxJava solution to the problem

    String title = "this is a title";
    StringBuilder stringBuilder = new StringBuilder();
    Observable.fromArray(title.trim().split("\\s"))
        .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
        .toList()
        .map(wordList -> {
            for (String word : wordList) {
                stringBuilder.append(word).append(" ");
            }
            return stringBuilder.toString();
        })
        .subscribe(result -> System.out.println(result));

I don't yet like the for loop inside map though.

Leftwich answered 10/4, 2018 at 10:41 Comment(0)
A
0

this is another way i did

    StringBuilder str=new StringBuilder("pirai sudie test test");

    str.setCharAt(0,Character.toUpperCase(str.charAt(0)));

    for(int i=str.length()-1;i>=0;i--)
    {
        if(Character.isSpaceChar(str.charAt(i)))
            str.setCharAt(i+1,Character.toUpperCase(str.charAt(i+1)));
    }

    System.out.println(str);
Atronna answered 9/11, 2018 at 7:40 Comment(0)
M
0

I made this little class that can be used to capitilize each word in a sentence. You can change the word separator in the string if this is not a space.

package com.ecnews.ecnews_v01.Helpers;

  public class Capitalize {

  String sentence;
  String separator = " ";

  public Capitalize(String sentence) {
    this.sentence = sentence;
  }

  public void setSeparator(String separator) {
    this.separator = separator;
  }

  public String getCapitalized() {
    StringBuilder capitalized = new StringBuilder("");
    for (String word : sentence.split(separator)) {
        capitalized.append(separator+Character.toUpperCase(word.charAt(0)) + word.substring(1));
    }
    return capitalized.toString().trim();
  }

}

Example:

String sourceName = new Capitalize("this is a test").getCapitalized();

sourceName will be "This Is A Test"

Much answered 16/2, 2019 at 12:20 Comment(0)
M
0

I just want to add an alternative solution for the problem by using only Java code. No extra library

public String Capitalize(String str) {

            String tt = "";
            String tempString = "";
            String tempName = str.trim().toLowerCase();
            String[] tempNameArr = tempName.split(" ");
            System.out.println("The size is " + tempNameArr.length);
            if (tempNameArr.length > 1) {
                for (String t : tempNameArr) {
                    tt += Capitalize(t);
                    tt += " ";
                }
                tempString  = tt;
            } else {
                tempString = tempName.replaceFirst(String.valueOf(tempName.charAt(0)), String.valueOf(tempName.charAt(0)).toUpperCase());
            }
            return tempString.trim();
        }
Maureen answered 7/5, 2019 at 13:6 Comment(0)
I
0
public static void main(String[] args) throws IOException {
    String words = "this is a test";

    System.out.println(Arrays.asList(words.split(" ")).stream().reduce("",(a, b)->(a + " " + b.substring(0, 1).toUpperCase() + b.substring(1))));


}

}

Immerge answered 12/5, 2019 at 17:41 Comment(1)
You can use Arrays.stream instead of turning it into a list first.Labors
I
0

Heres a lil program I was using to capitalize each first letter word in every subfolder of a parent directory.

private void capitalize(String string)
{
    List<String> delimiters = new ArrayList<>();
    delimiters.add(" ");
    delimiters.add("_");

    File folder = new File(string);
    String name = folder.getName();
    String[] characters = name.split("");

    String newName = "";
    boolean capitalizeNext = false;

    for (int i = 0; i < characters.length; i++)
    {
        String character = characters[i];

        if (capitalizeNext || i == 0)
        {
            newName += character.toUpperCase();
            capitalizeNext = false;
        }
        else
        {
            if (delimiters.contains(character)) capitalizeNext = true;
            newName += character;
        }
    }

    folder.renameTo(new File(folder.getParent() + File.separator + newName));
}
Irk answered 31/5, 2019 at 1:49 Comment(0)
S
0

You can also do it very simply like this and preserve any doubled and leading, trailing whitespaces

public static String capitalizeWords(String text) {

    StringBuilder sb = new StringBuilder();
    if(text.length()>0){
        sb.append(Character.toUpperCase(text.charAt(0)));
    }
    for (int i=1; i<text.length(); i++){
        String chPrev = String.valueOf(text.charAt(i-1));
        String ch = String.valueOf(text.charAt(i));

        if(Objects.equals(chPrev, " ")){
            sb.append(ch.toUpperCase());
        }else {
            sb.append(ch);
        }

    }

    return sb.toString();

}
Sputum answered 19/12, 2019 at 11:36 Comment(0)
B
0

I noticed in previous answers that referred to apache common utils, they either used the class WordUtils which is now deprecated, or they use StringUtils.capitalize() which only capitalizes the first word but not every single word in the sentence.

Here is a pure java solution to do this. Note: this will not work if there is a bit of punctuation in front of the word. Here's the function capitalizeEachWord(), but wrapped up in a main class so you can see a few basic tests cases.


import java.util.Optional;
import java.util.Objects;

class HelloWorld {
    public static void main(String[] args) {
        System.out.println(capitalizeEachWord(""));
        System.out.println(capitalizeEachWord("."));
        System.out.println(capitalizeEachWord(" ."));
        System.out.println(capitalizeEachWord(" . "));
        System.out.println(capitalizeEachWord("testing. 1 one 2 two 3 three"));
        System.out.println(capitalizeEachWord("testing. 1 one 2 two 3 three."));
        System.out.println(capitalizeEachWord("testing. 1 one 2 two 3 three "));
        System.out.println(capitalizeEachWord("testing. 1 one 2 two 3 three. "));
        System.out.println(capitalizeEachWord(" testing. 1 one 2 two 3 three"));
        System.out.println(capitalizeEachWord("!testing. 1 one 2 two 3 three."));
        System.out.println(capitalizeEachWord(" !testing. 1 one 2 two 3 three "));
        System.out.println(capitalizeEachWord(" !testing. 1 one 2 two 3 three "));
        System.out.println(capitalizeEachWord(" !testing. 1 one 2 two 3 three 4"));
    }
    
    
    private static String capitalizeEachWord(final String line) {
        return Optional.ofNullable(line)
            .filter(Objects::nonNull)
            .filter(givenLine -> givenLine.length() > 0)
            .map(givenLine -> {
                StringBuilder sb = new StringBuilder(givenLine);
                if(sb.charAt(0) != ' ') {
                    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
                }
                for (int i = 1; i < sb.length(); i++) {
                    if (sb.charAt(i - 1) == ' ') {
                        sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
                    }
                }
                return sb.toString();
            })
            .orElse(line);
    }
    
    
}

resulting output:

.
 .
 . 
Testing. 1 One 2 Two 3 Three
Testing. 1 One 2 Two 3 Three.
Testing. 1 One 2 Two 3 Three 
Testing. 1 One 2 Two 3 Three. 
 Testing. 1 One 2 Two 3 Three
!testing. 1 One 2 Two 3 Three.
 !testing. 1 One 2 Two 3 Three 
 !testing. 1 One 2 Two 3 Three 
 !testing. 1 One 2 Two 3 Three 4
Brunson answered 27/6, 2023 at 19:55 Comment(0)
E
-2

// So simple and basic

public void capalizedFirstCharOne(String str){
    char[] charArray=str.toCharArray();
    charArray[0]=Character.toUpperCase(charArray[0]);
    for(int i=1;i<charArray.length;i++){
        if(charArray[i]==' ' ){
            charArray[i+1]=Character.toUpperCase(charArray[i+1]);
        }
    }

    String result=new String(charArray);
    System.out.println(result);
}
Elmaelmajian answered 11/4, 2016 at 9:14 Comment(0)
R
-5
import java.io.*;
public class Upch2
{
   BufferedReader br= new BufferedReader( new InputStreamReader(System.in));
   public void main()throws IOException
    { 
        System.out.println("Pl. Enter A Line");
        String s=br.readLine();
        String s1=" ";
        s=" "+s;
        int len=s.length();
        s= s.toLowerCase();
        for(int j=1;j<len;j++)
         {
           char  ch=s.charAt(j);

           if(s.charAt(j-1)!=' ')
           {
             ch=Character.toLowerCase((s.charAt(j)));
           }
           else
           {
             ch=Character.toUpperCase((s.charAt(j)));
            }
            s1=s1+ch;
          }
     System.out.println(" "+s1);
  }
}
Roscoeroscommon answered 9/10, 2011 at 7:46 Comment(1)
far far too complexKohlrabi

© 2022 - 2024 — McMap. All rights reserved.