Java replace()问题

时间:2015-11-12 07:54:15

标签: java replace

我应该输入一个字符串,并将所有toyoufor&子字符串替换为2,{ {1}},U4

当我输入字符串"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

似乎在第一个空格

之后切断了返回的字符串

我不知道发生了什么,为什么它不能正常工作。 我做错了什么?

2 个答案:

答案 0 :(得分:1)

以下是我简化代码并获得正确结果的方法:

    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);

答案 1 :(得分:0)

将第一个Send("{SHIFTDOWN}{CTRLDOWN}{ALTDOWN}{+}{ALTUP}{CTRLUP}{SHIFTUP}") 替换为rope = rope.replace(" and "," & ");

现在它应该工作了。问题是您尝试替换的第一个“和”是rope = rope.replace("and "," & ");,而不是and,这就是为什么留下并且没有被替换的原因。

同时删除and的第二行,即simplifier。这是重复的,因为您已经在调用方法中打印结果。

更新: 我看到你在这里想做什么。试试这个:

对于要替换的每个单词,只需将其替换一次。因此对于System.out.print(rope);,请执行:

and

对于rope.replace("and", "&"); ,请执行:

to

不要在单词之间添加任何空格,没有必要。执行rope.replace("to", "2"); 一次将替换该单词的所有次出现。