无法替换字符串中的字符 [英] Unable to replace characters in a String

查看:106
本文介绍了无法替换字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试浏览一个字符数组,并用另一个数组中的并行字符替换字符串中的字符。

I am trying to go through an array of characters and replace that character in the string with the parallel character in the other array.

private String replace(String input)
{
    char[] first = {'a','e','o','s'};
    char[] second = {'@','3','0','$'};
    String myCopy = input.toLowerCase();


    for(int y = 0; y < first.length; y++)
    {
        myCopy.replace(first[y],second[y]);
    }


    return myCopy;
}

以下是我得到的例子:

Enter a string: as the dog runs here
Output: as the dog runs here

它总是输出相同的字符串而没有替换。

It always outputs the same string with no replacements.

我也尝试过使用:

myCopy.replace('a','@');

and

myCopy.replace("a","@");

和replaceAll方法。

and the replaceAll method.

任意建议?

推荐答案

字符串在Java中是不可变的。 replace()更改您调用它的字符串 - 返回带有更改的新字符串。所以你想要:

Strings are immutable in Java. replace() doesn't change the string you call it on - it returns a new string with the changes. So you want:

myCopy = myCopy.replace(first[y], second[y]);

所有 <$ c $上的方法也是如此c>字符串看起来正在改变它,因为它是不可变的。)

(The same is true for all the methods on String which "appear" to be changing it, as it's immutable.)

这篇关于无法替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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