Write a method numTWords that takes a String as a parameter and that returns the
ID: 3529473 • Letter: W
Question
Write a method numTWords that takes a String as a parameter and that returns the number of words in the String that start with the letter t (upper or lowercase). By definition, words are separated by one or more spaces. For example: numTWords("are there lots of t words here?") should return 2. Notice that words can contain punctuation marks. Any non-empty sequence of non-space characters can be a word. There might be spaces at the beginning or end of the String. For example: numTWords(" how about trick-or-treaters, candy, and cats? ") should return 1. You may not construct any other objects to solve this problem (e.g., you canExplanation / Answer
public int numTWords(String str) {
StringTokenizer st = new StringTokenizer(str," "); //space as delimter
int count = 0;
if(st.countTokens() > 0 ) {
while(st.hasMoreTokens()) {
String temp = st.nextToken();
if(temp.trim().startsWith("t"))
count++;
}
}
return count;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.