Java replace()问题

问题描述

这是我简化您的代码并获得正确结果的方式:

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

解决方法

我应该输入一个字符串,并更换所有and,to,you,和for与子&,2,U,和4。

输入字符串时"and,and,to,you,for,a,e,i,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

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

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

猜你在找的技术问答相关文章

如何检查配对的蓝牙设备是打印机还是扫描仪(Android)
是否允许实体正文进行HTTP DELETE请求?
如何将ZipInputStream转换为InputStream?
java.util.logging Java 8中的变量
PowerMockito.doReturn返回null
Java中的RESTful调用
Swing / Java:如何正确使用getText和setText字符串
特殊字符和重音字符
Android Studio中的ndk.dir错误
错误“找不到主类”