java – StringBuilder insert method
This line is the problem:
stringBuilder.insert(0, first); //insert the copied character at the beginning of the substring
stringBuilder here does not represent the current substring, but instead the final decrypted string that you are trying to build. That is why the value is getting added to the beginning of the entire string.
You have several options:
You can add the resulting string from
stringBuilderat the end of the loop to
builder2, then clear the
stringBuilder. From how your code was written, I imagine this is what you were expecting:
Note that you would also remove the
builder2.append(decryptedSS);that you have outside the loop.
You could save the length of
stringBuilderat the start of the loop, and insert into that value instead of 0.
You can fully modify
subStrin your loop, and append the completed version to
stringBuilderat the end of the loop.