Situation:
A user will input a sentence. I need to perform certain modifications to each word but depending on the length of each word.
For example for each vowel i need to put a 3 before if the word length is over 2.
// for words with length > 2
for (i=0;i<example.length();i++)
switch (word.charAt(i))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
output += "3" + word.charAt(i);
break;
default:
output += word.charAt(i);
break;
}
Objective:
How can i test a word's length before i perform my for loop. Say my word is 1-character long, i need to put a "1", 2-character long a "2".
Example:
"hello my name is roger"
Output:
h3ell3o m2y n3am3e 2is 1A
Important:
No arrays, only for, while loops, switch or if statements.
public class Test {
public static void main(String[] args) {
String input = "hello my name is roger";
input+=' '; // adding a whitespace at end to indicate completion of last word
String word = "";
char ch;
String res = "";
int len = input.length();
for(int i = 0;i<len ;i++) {
ch = input.charAt(i);
if(Character.isWhitespace(ch)) {
res = res +" "+processWord(word);
System.out.println(word);
word = "";
}else {
word+=ch;
}
}
}
private static String processWord(String word) {
// TODO Auto-generated method stub
if(word.length()<=2) {
return word;
}
// do whatever you have to do with your word
String res = "";
return res;
}
}
Basically,The logic to extract out words is -
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.