JAVA替换一个String,无需多次替换
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);
上面是我用来替换从 TextArea (tIn -> p) 中读取的字符串的代码,然后有一个标签数组 (lChar),我在其中存储每个唯一的字符(字符值是数组索引)和我还有一个 TextField 数组(tReplace),在这里我为 lChar 中的每个字符编写替换字符串(可以是多个字符)(“旧”字符中的字符值是数组索引)。
所以现在我想用 tReplace 中的每个字符替换 lChar 中的每个字符。如果我想将字符串“12”的“1”替换为“2”,将“2”替换为“1”,我会得到“11”,因为在第一个循环中它将其更改为“22”,而在下一个循环中它将其更改为“11”。但我只想改变每个字母一次,就好像我会写
String.valueOf(21).replace("2","1").replace("1","2");
任何想法如何做到这一点?
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).
So now I want to replace every char in lChar with every char in tReplace. 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'. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为此任务创建一个自动机:
使用
String.getChars()
将字符串转换为char[],然后迭代数组,根据需要替换每个字符。注意:如果需要用长度大于 1 的字符串替换每个字符,可以使用相同的方法,但使用 char[],使用 StringBuilder,并且对于每个字符:如果需要替换,将替换字符串追加到 StringBuilder,否则:将 char 追加到 StringBuilder
示例代码:
将导致:
221221
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.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
sample code:
will result in:
221221