Java replace()问题 [英] Java replace() problems

查看:139
本文介绍了Java replace()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该输入一个字符串,并将所有替换为 子串,& 2 U 4

I'm supposed to input a string, and replace all and, to, you, and for substrings with &, 2, U, and 4.

当我输入字符串和,和,to,to,to,to,your,you,for,for,for,a,a,e,e,i, i,o,o,u,u,打印时只输出

When I input the string "and , and,and , to , to,to , you ,you , you, for ,for , for,a , a,e , e,i , i,o , o,u , u", it only outputs and when I print it.

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

输出:

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

It seems to cut off the returned string after the first space

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

I have no idea what is going on and why it is not working as it should. What am I doing wrong?

推荐答案

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

Here is how I simplified your code and got the correct result:

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

这篇关于Java replace()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆