Apex String Manipulation – How to Append to a String Until Last Character

apexcontrollerlightning-web-componentsstring

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:

initialAppend+H+middleAppend+E+middleAppend+L+middleAppend+L+middleAppend+O+finalAppend

I tried this but it doean't work

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

do{
    if(i<myInput.length()){
        system.debug('\n\n'+myInput.substring(i,i+toAppendFinal));
    }
    i=i+1;
}while(i < myInput.length());

Best Answer

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);

Related Topic