1

I am a beginner in Java trying to write a program to convert strings into title case. For example, if String s = "my name is milind", then the output should be "My Name Is Milind".

import java.util.*;
class TitleCase
{
public static void main(String args[])
{
    Scanner in = new Scanner(System.in);
    System.out.println("ent");

    String s=in.nextLine();
    String str ="";        
    char a ;

    for(int i =0;i<s.length()-1;i++)
    {
        a = s.charAt(i);
        if(a==' ')
        {
            str = str+(Character.toUpperCase(s.charAt(i+1)));
        }
        else
        {
            str =str+(Character.toLowerCase(a));
        }

    }

    //for(int i =0; i<s.length();i++)
    //{
        System.out.println(str);
    //}
}
}
user812786
  • 4,302
  • 5
  • 38
  • 50
Milind Rajpoot
  • 11
  • 1
  • 1
  • 3
  • 2
    Welcome to Stack Overflow! Can you include the specific error message or problem you are having? – user812786 Jan 22 '16 at 14:36
  • Some hints: In your first if statement, you are checking against the character at position `i`, but you are only adding the character at position `i+1`. What happens to the space? What will happen at the next iteration of the for loop? – user812786 Jan 22 '16 at 14:45
  • Possible duplicate of https://stackoverflow.com/questions/1086123/string-conversion-to-title-case – Atul KS Sep 18 '19 at 17:15
  • Does this answer your question? [How to capitalize the first character of each word in a string](https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string) – M. Justin Dec 14 '22 at 19:53

9 Answers9

4

You are trying to capitalize every word of the input. So you have to do following steps:

  1. get the words separated
  2. capitalize each word
  3. put it all together
  4. print it out

Example Code:

  public static void main(String args[]){
     Scanner in = new Scanner(System.in);
     System.out.println("ent");

     String s=in.nextLine();

     //now your input string is storred inside s.
     //next we have to separate the words.
     //here i am using the split method (split on each space);
     String[] words = s.split(" ");

     //next step is to do the capitalizing for each word
     //so use a loop to itarate through the array
     for(int i = 0; i< words.length; i++){
        //we will save the capitalized word in the same place again
        //first, geht the character on first position 
        //(words[i].charAt(0))
        //next, convert it to upercase (Character.toUppercase())
        //then add the rest of the word (words[i].substring(1))
        //and store the output back in the array (words[i] = ...)
        words[i] = Character.toUpperCase(words[i].charAt(0)) + 
                  [i].substring(1);
     }

    //now we have to make a string out of the array, for that we have to 
    // seprate the words with a space again
    //you can do this in the same loop, when you are capitalizing the 
    // words!
    String out = "";
    for(int i = 0; i<words.length; i++){
       //append each word to out 
       //and append a space after each word
       out += words[i] + " ";
    }

    //print the result
    System.out.println(out);
 }
Jarlik Stepsto
  • 1,667
  • 13
  • 18
4

Using Java 8 streams:

String titleCase = (new ArrayList<>(Arrays.asList(inputString.toLowerCase().split(" "))))
                   .stream()
                   .map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1))
                   .collect(Collectors.joining(" "));
MarcBate
  • 51
  • 3
  • You don't need to convert the Array to a List, or to then convert that list to an ArrayList. You can more simply write `Arrays.stream(inputString.toLowerCase().split(" ")).map(...).collect(...)` – charles-allen Jul 03 '17 at 18:01
2

You want to change the case of the first letter of each word of a String.

To do so, I would follow the following steps :

Aaron
  • 24,009
  • 2
  • 33
  • 57
2

The problem is with the way you're adding characters. Take a look at your if condition:

a = s.charAt(i);
if(a==' ')
{
    // Here you are adding not the current character, but the NEXT character.
    str = str+(Character.toUpperCase(s.charAt(i+1)));
}
else
{
    // Here you are adding the current character. 
    str =str+(Character.toLowerCase(a));
}

As a result of this condition, you will skip a character if your input string contains a space, then repeat another character that you've already added.

Additionally, you're not looping through the whole string because your loop conditional goes to s.length()-1. Change that to just s.length(). However, if you do that, you may run into an exception if the input string ends with a space (since you'll try to check for a character at an out-of-bound index).

Here's what the fixed code would look like:

public static void main(String args[])
{
    Scanner in = new Scanner(System.in);
    System.out.println("ent");

    String s=in.nextLine();
    String str ="";        
    char a ;

    for(int i =0;i<s.length();i++)
    {
        a = s.charAt(i);
        if(a==' ')
        {
            str = str+Character.toLowerCase(a)+(Character.toUpperCase(s.charAt(i+1)));
            i++; // "skip" the next element since it is now already processed
        }
        else
        {
            str =str+(Character.toLowerCase(a));
        }

    }
    System.out.println(str);
}

NOTE: I only fixed the code that you supplied. However, I'm not sure it works the way you want it to - the first character of the string will still be whatever case it started in. Your conditional only uppercases letters that are preceded by a space.

Mage Xy
  • 1,803
  • 30
  • 36
  • Thank you Mage Xy your reply works but the first charcter has to be changed and i'll do it myself..............Thank you once mor – Milind Rajpoot Jan 22 '16 at 15:06
2

Code Golf variation... I challenge anyone to make it any simpler than this:

public String titleCase(String str) {
    return Arrays
            .stream(str.split(" "))
            .map(String::toLowerCase)
            .map(StringUtils::capitalize)
            .collect(Collectors.joining(" "));
}
Alex R
  • 11,364
  • 15
  • 100
  • 180
1

By the way: Unicode distinguishes between three cases: lower case, upper case and title case. Although it does not matter for English, there are other languages where the title case of a character does not match the upper case version. So you should use

Character.toTitleCase(ch)

instead of Character.toUpperCase(ch) for the first letter.

There are three character cases in Unicode: upper, lower, and title. Uppercase and lowercase are familiar to most people. Titlecase distinguishes characters that are made up of multiple components and are written differently when used in titles, where the first letter in a word is traditionally capitalized. For example, in the string "ljepotica",[2] the first letter is the lowercase letter lj(\u01C9 , a letter in the Extended Latin character set that is used in writing Croatian digraphs). If the word appeared in a book title, and you wanted the first letter of each word to be in uppercase, the correct process would be to use toTitleCase on the first letter of each word, giving you "Ljepotica" (using Lj, which is \u01C8). If you incorrectly used toUpperCase, you would get the erroneous string "LJepotica" (using LJ, which is \u01C7).

[The Java™ Programming Language, Fourth Edition, by James Gosling, Ken Arnold, David Holmes (Prentice Hall). Copyright 2006 Sun Microsystems, Inc., 9780321349804]

1

WordUtils.capitalizeFully() worked for me like charm as it gives: WordUtils.capitalizeFully("i am FINE") = "I Am Fine"

Atul KS
  • 908
  • 11
  • 21
0
import java.util.Scanner;

public class TitleCase {
    public static void main(String[] args) {
        System.out.println("please enter the string");
        Scanner sc1 = new Scanner(System.in);
        String str = sc1.nextLine();
        //whatever the format entered by user, converting it into lowercase
        str = str.toLowerCase();
        // converting string to char array for 
        //performing operation on individual elements
        char ch[] = str.toCharArray();
        System.out.println("===============");
        System.out.println(str);
        System.out.println("===============");
        //First letter of senetence must be uppercase
        System.out.print((char) (ch[0] - 32));
        for (int i = 1; i < ch.length; i++) {
            if (ch[i] == ' ') {
                System.out.print(" " + (char) (ch[i + 1] - 32));
                //considering next variable after space
                i++;
                continue;
            }
            System.out.print(ch[i]);
        }
    }
}
-1

You can use lamda instead-

String titalName = Arrays.stream(names.split(" "))
                                       .map(E -> String.valueOf(E.charAt(0))+E.substring(1))
                                       .reduce(" ", String::concat);