![](/img/trans.png)
[英]How can I reverse a string word by word without using arrays, split() or StringBuilder
[英]How can i extract a word using loops and not arrays
情况:
用户将输入句子。 我需要对每个单词进行某些修改,但要取决于每个单词的长度。
例如,对于每个元音,如果单词长度超过2,我需要在前面加上3。
// 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;
}
目的:
在执行for循环之前,如何测试单词的长度。 假设我的单词长1个字符,我需要输入一个“ 1”,2个字符长一个“ 2”。
例:
“你好,我叫罗杰”
输出:
h3ell3o m2y n3am3e 2is 1A
重要:
没有数组,仅用于while循环,switch或if语句。
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;
}
}
基本上,提取单词的逻辑是-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.