Convert String into Title Case

前端 未结 9 1298
终归单人心
终归单人心 2021-01-03 15:09

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 b

相关标签:
9条回答
  • 2021-01-03 16:04

    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.

    0 讨论(0)
  • 2021-01-03 16:04

    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 :

    • split the String in words : see String.split(separator)
    • retrieve the first letter of each word : see String.charAt(index)
    • retrieve its capitalized version : the Character.toUpperCase(char) you use is perfect
    • concatenate the capitalized letter with the rest of the word : concatenation operator (+) and String.substring
    • create a new String from the capitalized words : see String.join(separator)
    0 讨论(0)
  • 2021-01-03 16:04

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

    0 讨论(0)
提交回复
热议问题