java – StringBuilder insert method

java – StringBuilder insert method

This line is the problem:

stringBuilder.insert(0, first); //insert the copied character at the beginning of the substring

the 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:

  1. You can add the resulting string from stringBuilder at 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:

    builder2.append(decryptedSS); 
    stringBuilder.setLength(0); 
    

    Note that you would also remove the builder2.append(decryptedSS); that you have outside the loop.

  2. You could save the length of stringBuilder at the start of the loop, and insert into that value instead of 0.

  3. You can fully modify subStr in your loop, and append the completed version to stringBuilder at the end of the loop.

java – StringBuilder insert method

Leave a Reply

Your email address will not be published. Required fields are marked *