Word separator

The problem

Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string “StopAndSmellTheRoses.” would be converted to “Stop and smell the roses.”

Breaking it down

We will split a string by a regular expression on uppercase characters and retain the delimiters by using look ahead and look behind. Next we will use a standard for loop to iterate over elements, if it is the first element we will add it to sentenceElements, otherwise adding it calling toLowerCase() for proper punctuation. Finally using the java 8 StringJoiner class we will join elements of a list with a space.

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get a string from the user.
    System.out.println("Enter a sentence with no spaces "
            + "between the words and each " + "word is capitalized.");
    System.out.println("An example is: StopAndSmellTheRoses");
    System.out.print("> ");

    // get user input
    String userInput = keyboard.nextLine();

    // close keyboard

    List<String> sentenceElements = Arrays.stream(

    // properly format sentence
    List<String> sentence = new ArrayList<>();
    for (int x = 0; x < sentenceElements.size(); x++) {
        if (x == 0) {
        } else {

    System.out.println(String.join(" ", sentence));


Enter a sentence with no spaces between the words and each word is capitalized.
An example is: StopAndSmellTheRoses
> StopAndSmellTheRoses
Stop and smell the roses