I am trying to eventually replace a sentence with another set of String. But I hit a roadblock while trying to replace a char in a String with another character of another String.
Here's what I have so far.
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
//swapping each char of 'sentence' with the chars in 'encode'
for (int i = 0; i < sentence.length(); i++) {
int indexForEncode = letters.indexOf(sentence.charAt(i));
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
}
System.out.println(sentence);
This way of replacing characters doesn't work. Can someone help me?
Kevin Anderson :
The reason\nsentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));\n\ndoesn't work is that Strings are immutable (i.e., they never change).\nSo, sentence.replace(...) doesn't actually change sentence; rather, it returns a new String. You would need to write sentence = sentence.replace(...) to capture that result back in sentence.\nOK, Strings 101: class dismissed (;->).\nNow with all that said, you really don't want want to keep reassigning your partially encoded sentence back to itself, because you will, almost certainly, find yourself re-encoding characters of sentence that you already encoded. Best to leave sentence in its original form while building up the encoded string one character at a time like this:\nStringBuilder sb = new StringBuilder();\nfor (int i = 0; i < sentence.length(); i++){\n int indexForEncode = letters.indexOf(sentence.charAt(i));\n sb.append(indexForEncode != -1\n ? encode.charAt(indexForEncode)\n : sentence.charAt(i)\n );\n}\nsentence = sb.toString();\n",
2021-03-18T01:39:42
WJS :
I would use a character array as follows. Make the changes to a character array and then use String.valueOf to get the new version of the string.\nString letters = "abcdefghijklmnopqrstuvwxyz";\nString encode = "kngcadsxbvfhjtiumylzqropwe";\n// the sentence that I want to encode\nString sentence = "hello, nice to meet you!";\n\nchar[] chars = sentence.toCharArray();\nfor (int i = 0; i < chars.length; i++){\n int indexForEncode = letters.indexOf(sentence.charAt(i));\n // if index is < 0, use original character, otherwise, encode.\n chars[i] = indexForEncode < 0 ? chars[i] : encode.charAt(indexForEncode);\n}\nSystem.out.println(String.valueOf(chars));\n\nPrints\nxahhi, tbga zi jaaz wiq!\n",
2021-03-18T02:02:30