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
keyboard . close ();
List < String > sentenceElements = Arrays . stream (
userInput . split ( "(?=[A-Z])" )). collect ( Collectors . toList ());
// properly format sentence
List < String > sentence = new ArrayList <>();
for ( int x = 0 ; x < sentenceElements . size (); x ++) {
if ( x == 0 ) {
sentence . add ( sentenceElements . get ( x ));
} else {
sentence . add ( sentenceElements . get ( x ). toLowerCase ());
}
}
System . out . println ( String . join ( " " , sentence ));
}
Output Enter a sentence with no spaces between the words and each word is capitalized.
An example is: StopAndSmellTheRoses
> StopAndSmellTheRoses
Stop and smell the roses
Word separator posted by Justin Musgrove on 28 October 2014
Tagged: java and java-exercises-beginner
Share on: Facebook Google+