package num20;
import TurtleGraphics.KeyboardReader;
public class Num20main {
public static void main(String[] args) {
KeyboardReader reader = new KeyboardReader();
System.out.println("Enter String");
String sentence = reader.readLine();
StringBuilder sb = new StringBuilder(sentence);
System.out.println(sb.toString());
//String e = "egg";
for(int x = 0; x < sentence.length(); x++){
String e = "egg";
char l = sb.charAt(x);
int index = x;
if(l == ('a') || l == ('A') || l == ('e') || l == ('E') || l == ('I') || l == ('i') || l == ('O') || l == ('o') || l == ('U') || l == ('u')){
sb.insert(index, e);
System.out.println(sb.toString());
}
}
System.out.println(sb.toString());
}
}
此代码打印出来:
输入字符串
我爱Java
我爱Java
eggI Love Java
eggeggI Love Java
eggeggeggI Love Java
eggeggeggeggI Love Java
eggeggeggeggI Love Java
它应该打印出“eggI Leggovegge Jeggavegga”
答案 0 :(得分:1)
您正在添加String的开头。 所以发生了什么,你添加“鸡蛋”,但你的索引不会前进。 “我喜欢java”'我'在索引0。 但是当你添加一个“鸡蛋”时,我们就有了“eggI love java”。 现在'我'在索引3处,但此时你的x是1。
最简单的方法是以相反的方式运行:
for(int x = sentence.length()-1 ; x <= 0 ; x--){ //The content of your for here }
这样做,添加“鸡蛋”不会影响您的功能。
答案 1 :(得分:0)
尝试这种方式:
String sentence = "I love Java";
System.out.println(Arrays.stream(sentence.split(" ")).map(str -> str.replaceAll("(?i)[aeiou]", "fruit$0")).collect(Collectors.joining(" ")));
基本上,您首先进行不区分大小写的查找,然后将匹配替换为匹配+&#34;水果&#34;。
答案 2 :(得分:0)
您的索引以与x相同的速度移动,但每次替换时,您插入3而不是1个字符。
我使用了一个固定的String来进行简单的测试,并且为了便于控制,最后添加了预期的结果:
public class Num20 {
public static void main(String[] args) {
String sentence = "I Love Java";
StringBuilder sb = new StringBuilder(sentence);
System.out.println(sb.toString());
// String e = "egg"; Good idea to declare this unchanged variable
// here, but let us call it 'egg'.
String egg = "egg";
int index = 0; // index out of loop
for (int x = 0; x < sentence.length(); x++){
char l = sb.charAt (index); // sb is under constant change,
// we need to insert at a the place of sb, not sentence
// hence we use the faster moving index 'index', not 'x'
// if (l == ('a') || l == ('A') || l == ('e') || l == ('E') || l == ('I') || l == ('i') || l == ('O') || l == ('o') || l == ('U') || l == ('u')) {
// not wrong, but more brief:
if ("aeiouAEIOU".indexOf (l) != -1) {
sb.insert (index, egg);
System.out.println(sb.toString());
// we inserted 3 characters before the vowel
index +=3;
}
// we have to forward one (more) step for every x in sentence, too:
++index;
}
System.out.println(sb.toString());
System.out.println("eggI Leggovegge Jeggavegga?");
}
}