I'm asking how to append 3 types of strings (initial, middle and final) to each character of an input string

example: "hello" -> I want to have:


I tried this but it doean't work

String myInput ='hello';
Integer i=0;
String toAppendInitial = 'initialAppend';
String toAppendMiddle = 'middleAppend';
String toAppendFinal = 'finalAppend';

}while(i < myInput.length());

1 Answer 1


This is one of the unique scenarios I have seen. Is it some kind of academic/interview question? Curious to know real-life scenario for the same.

However, try below code - Here the split() will seperate each letter of that word and join method will add that provided word with each seperated letter.

String myInput ='hello';
String toAppendInitial = 'initialAppend';
String toAppendMiddle = 'middleAppend';
String toAppendFinal = 'finalAppend';

String output = toAppendInitial + String.join(myInput.split(''), toAppendMiddle) + toAppendFinal;
System.debug('Output: ' + output);

  • I hate this scenario too, but it is for a real work case I tried you code but it prints only : |USER_DEBUG|[7]|DEBUG|Output: initialAppendhmiddleAppendemiddleAppendlmiddleAppendlmiddleAppendofinalAppend without the letters of the word
    – MashaMasha
    Jul 8, 2022 at 12:59
  • 1
    oh yes, i'm blind, sorry dude! thank you very much!!
    – MashaMasha
    Jul 8, 2022 at 13:00
  • if it works, mark it as an accepted answer :)
    – Ysr Shk
    Jul 8, 2022 at 13:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .