Text Processing and More about Wrapper Classes 1, Word Counter Write a method th
ID: 3547641 • Letter: T
Question
Text Processing and More about Wrapper Classes
1, Word Counter
Write a method that accepts a String object as an argument and returns the number of words it contains. For instance, if the argument is "Four score and seven years ago" the method should return the number 6. Demonstrate the method in a program that asks the user to input a string and then passes it to the method. The number of words in the string should be displayed on the screen.
2, Word Separator
Write a program that accepts as 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."
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args)
{
String str1 = new String("Four score and seven years ago");
int words;
words = wordCounter(str1);
System.out.println(words);
}
public static int wordCounter(String input)
{
int len,count=0;
len = input.length();
for(int i=0;i<len;i++)
{
if(input.charAt(i)==' ')
{
count++;
}
}
return count+1;
}
}
____________________________________________________________________________
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone1
{
public static void main (String[] args)
{
String str2 = new String("StopAndSmellTheRoses.");
String output;
output = wordSeperator(str2);
System.out.println(output);
}
public static String wordSeperator(String input)
{
StringBuilder output = new StringBuilder("");
int len;
len = input.length();
for(int i=0;i<len;i++)
{
if(input.charAt(i)>='A' && input.charAt(i)<='Z')
{
if(i!=0)
output.append(' ');
output.append(input.charAt(i));
}
else
{
output.append(input.charAt(i));
}
}
return output.toString();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.