Convert String into Title Case

前端 未结 9 1388
终归单人心
终归单人心 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

    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.

提交回复
热议问题