简体   繁体   English

JAVA替换字符串而无需多次替换

[英]JAVA replacing a String without replacing it many times

String _p = p;      
for(int i = 0; i <= _p.length()-1; i++)
   _p = _p.replace(lChar[_p.charAt(i)].getText(), tReplace[_p.charAt(i)].getText());
tOut.append(_p);

Above is the code I use to replace a string which I read out of a TextArea (tIn -> p), then there is a Label Array (lChar) where I store every unique char (the char value is the Array index) and I have also a TextField Array (tReplace) here I write the replace string (which can be multiple chars) for every char in lChar (the char value from the 'old' char is the Array index). 上面的代码是我用来替换从TextArea(tIn-> p)中读取的字符串的代码,然后有一个Label Array(lChar),我在其中存储了每个唯一的char(char值是Array索引),并且还有一个TextField Array(tReplace),在这里我为lChar中的每个字符写替换字符串(可以是多个字符)(“旧”字符中的char值是数组索引)。

So now I want to replace every char in lChar with every char in tReplace. 所以现在我想用tReplace中的每个字符替换lChar中的每个字符。 If i want to replace '1' with '2' and '2' with '1' for the string '12' I get '11', because in the first loop it changes it to '22' and in the next loop it changes it to '11'. 如果我想用'2'替换'1'并用'1'替换'2'我得到'11',因为在第一个循环中它将更改为'22',在下一个循环中将其更改为'22'将其更改为“ 11”。 BUT I only want to change every letter once as if i would write 但是我只想改变每个字母一次,就像我会写

String.valueOf(21).replace("2","1").replace("1","2");

Any ideas how to do this? 任何想法如何做到这一点?

you can create an automaton for this task: 您可以为此任务创建一个自动机:
cast your String to char[] using String.getChars() and then iterate over the array, replace each char as desired. 使用String.getChars()将您的String转换为char [],然后遍历数组,根据需要替换每个char。
note: if you need to replace each char with a string which its length is >1, you can use the same approach, but instead using a char[], use a StringBuilder, and for each char: if it needs to be replaced, append the replacing-string to the StringBuilder, else: append the char to the StringBuilder 注意:如果您需要用长度大于1的字符串替换每个字符,则可以使用相同的方法,但是要使用char []代替,而是使用StringBuilder,对于每个字符:如果需要替换,将替换字符串附加到StringBuilder,否则:将char附加到StringBuilder
sample code: 样例代码:

String original = "1212";
        HashMap<Character, String> map = new HashMap<Character, String>();
        map.put('1', "22");
        map.put('2', "1");
        StringBuilder sb = new StringBuilder();
        for (int i =0;i<original.length();i++) {
            char ch = original.charAt(i);
            if (map.containsKey(ch)) {
                sb.append(map.get(ch));
            } else {
                sb.append(ch);
            }
        }
        System.out.println(sb);

will result in: 221221 将导致: 221221

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM