Percy

Java replace()问题

java

我应该输入一个字符串,并更换所有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

似乎在第一个空格后切断了返回的字符串

我不知道发生了什么,为什么不按预期工作。我究竟做错了什么?


阅读 427

收藏
2020-12-07

共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);
2020-12-07