Prompt the user to enter a sentence. Output that sentence with spacing corrected
ID: 3638930 • Letter: P
Question
Prompt the user to enter a sentence. Output that sentence with spacing corrected and with letters corrected for capitalization. In other words, in the output sentence, all strings of two or more blanks should be compressed to a single blank. The sentence should start with an upper case letter but should contain no other uppercase letters. Do not worry about proper names. Treat a line break as if it were a blank, in that a line break and any number of blanks are compressed to a single blank.. Assume the sentence ends with a period and contain no other periods. For example, the input:the Answer to life, the Universe, and everything
IS 42
should produce the following output:
The answer to life, the universe, and everything is 42.
Explanation / Answer
/**
*
Operations on Strings that contain Sentence.
*
*
This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* @author deepu
*/
public class SentenceUtil {
public SentenceUtil(){
super();
}
/**
*
Capitalizes all the . separated Sentences in a String.
* Only the first letter of each Sentence is changed.
*
*
A null input String returns null.
* Capitalization uses the unicode title case, normally equivalent to
* upper case.
*
*
*
* @param str the String to capitalize, may be null
* @return capitalized String, null if null String input
*/
public static String capitalize(String string){
if(string == null)
return string;
String[] stArray = string.split("\.");
StringBuffer sb = new StringBuffer();
for(int i=0;i String temp = stArray[i];
temp = temp.trim();
sb.append(temp.substring(0,1).toUpperCase());
sb.append(temp.substring(1,temp.length()).toLowerCase());
sb.append(". ");
}
return sb.toString();
}
/**
* Main Method for testing.
* @param args
*/
public static void main(String[] args) {
System.out.println("REQUEST: hELLO hOW Are yOu. i Am fine Here.");
System.out.println("RESULT: "+SentenceUtil.capitalize("hELLO hOW Are yOu. i Am fine Here."));
System.out.println("REQUEST: the Answer to life, the Universe, and everything IS 42");
System.out.println("RESULT: "+SentenceUtil.capitalize("the Answer to life, the Universe, and everything IS 42"));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.