有效的方式来替换字符串中的字符(java)? [英] Efficient way to replace chars in a string (java)?

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

问题描述

我在写一个小型的JAVA程序,它:

I'm writing a small JAVA program which:


  • 将文本作为字符串

  • 需要2个字符数组

我试图做的事听起来像是find and replace,但是不一样我认为重要的是要清除它。

What im trying to do will sound like "find and replace" but it is not the same so i thought its important to clear it.

无论如何,我想要获取这个文本,如果第一个数组中的任何字符匹配文本中的一个字符,如果是,替换

Anyway I want to take this text, find if any char from the first array match a char in the text and if so, replace it with the matching char (according to index) from the second char array.

我将用一个例子解释:
让我说我的文本(String) is:java is awesome!;
i有两个数组(char []):absm和!@ * $。

I'll explain with an example: lets say my text (String) is: "java is awesome!"; i have 2 arrays (char[]): "absm" and "!@*$".

希望的结果是将'a' !','b'到'@'等等。
意味着结果文本将是:

The wished result is to change 'a' to '!' , 'b' to '@' and so on.. meaning the resulted text will be:

java is awesome!改为 - >j @ v @ i * @ w * o $ e!

StringBuilder / String class可以使用)

(StringBuilder/String class can be used)

推荐答案

StringBuilder sb = new StringBuilder(text);
    for(int i = 0; i<text.length(); i ++)
    {
        for (int j = 0; j < firstCharArray.length;j++)
        {
            if (sb.charAt(i) == firstCharArray[j])
            {
                sb.setCharAt(i, secondCharArray[j]);
                break;
            }

        }
    }

是有效率的,因为它使用StringBuilder来改变字符的位置(如果你使用字符串,你将不得不每次创建新的,因为它们是不可变的)。它也最小化了你需要做的传递量(1通过文本string和n通过第一个数组,其中n = text.length())

This way is efficient because it uses a StringBuilder to change the characters in place (if you used Strings you would have to create new ones each time because they are immutable.) Also it minimizes the amount of passes you have to do (1 pass through the text string and n passes through the first array where n = text.length())

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

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