我应该输入一个字符串,并将所有and、to、you和for子字符串替换为&、2、U和4。
当我输入字符串"and , and,and , to , to,to , you ,you , you, for ,for , for,a , a,e , e,i , i,o , o,u , u"时,它只在打印它时输出and。
public void simplify()
{
System.out.println("Enter a string to simplify: ");
String rope = in.next();
System.out.println(simplifier(rope));
}
public String simplifier(String rope)
{
rope = rope.replace(" and "," & ");
rope = rope.replace(" and"," &");
rope = rope.replace("and ","& ");
rope = rope.replace(" to "," 2 ");
rope = rope.replace(" to"," 2");
rope = rope.replace("to ","2 ");
rope = rope.replace(" you "," U ");
rope = rope.replace("you ","U ");
rope = rope.replace(" you"," U");
rope = rope.replace(" for "," 4 ");
rope = rope.replace("for ","4 ");
rope = rope.replace(" for"," 4");
rope = rope.replace("a ","");
rope = rope.replace(" a","");
rope = rope.replace("e ","");
rope = rope.replace(" e","");
rope = rope.replace("i ","");
rope = rope.replace(" i","");
rope = rope.replace(" o","");
rope = rope.replace("o ","");
rope = rope.replace("u ","");
rope = rope.replace(" u","");
System.out.print(rope);
return rope;
}输出:and and
它似乎在第一个空格之后切断了返回的字符串。
我不知道这是怎么回事,也不知道它为什么不能正常工作。我做错了什么?
发布于 2015-11-12 08:48:59
下面是我如何简化您的代码并得到正确的结果:
String rope = "and , and,and , to , to,to , you ,you , you, for ,for , for,a , a,e , e,i , i,o , o,u , u";
// rope = rope.replaceAll(" ", "");
rope = rope.replaceAll("and", "&");
rope = rope.replaceAll("to", "2");
rope = rope.replaceAll("you", "U");
rope = rope.replaceAll("for", "4");
rope = rope.replaceAll("a", "");
rope = rope.replaceAll("e", "");
rope = rope.replaceAll("i", "");
rope = rope.replaceAll("o", "");
rope = rope.replaceAll("u", "");
System.out.println(rope);发布于 2015-11-12 08:35:13
将第一个rope = rope.replace(" and "," & ");替换为rope = rope.replace("and "," & ");
现在该起作用了。问题是,第一个“和”您试图替换的是and,而不是and,这就是为什么会留下而没有被替换。
还删除simplifier的第二行,即System.out.print(rope);。这是重复的,因为您已经在调用方法中打印结果。
更新:我明白你在做什么了。试试这个:
对于要替换的每个单词,只替换一次。因此,对于and,请做:
rope.replace("and", "&");对于to,请执行以下操作:
rope.replace("to", "2");不在单词之间添加任何空格,这是不必要的。执行replace()一次将取代所有的出现的那个单词。
https://stackoverflow.com/questions/33666602
复制相似问题