Reputation: 3
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?
Upvotes: 0
Views: 1410
Reputation: 178491
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:
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
Upvotes: 1