javastringsubstringindexofcharat

Make second word capital in a string


I don't really know how to explain the problem. I do have a scanner imported after the package. I'm not sure if you can stack methods, and if you can I'm definitely doing it wrong.

Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");

String name = console.next();
name.trim();
name.toUpperCase(name.substring(name.charAt(name.indexOf(" "))));

System.out.println("Your name is: " + name);

Solution

  • Just split the String into the first word and second word based on the indexOf(" ")

    Capitalize the second word using toUpperCase

    Concatenate both words together using +

    name = name.substring(0, name.indexOf(" ")) + name.substring(name.indexOf(" ")).toUpperCase();
    

    Note: Not sure if you are required to handle invalid input, but this code would only work assuming a valid two-word name is entered, with a space in-between

    Also, make sure to change console.next() to console.nextLine() to ensure you retrieve the entire line of input