Search code examples
salesforceapex-codeapex

How can I get whole string value from List in apex


I need your help. I made an apex class which is giving output like (1,i,n,d,i,a,,1,2,3) and I would like to show output as a whole string format like(1india 123). I tried many different ways but couldn't get what I actually want. Here is my apex class:-

public class Assign2{

public void testFunction(String str ,integer num){
    integer rem,temp = 0;  
    integer sumOfDigit = 0;
    List<String> stringCharacters = new List<String>();
    List<String> inputStr = new List<String>();

        stringCharacters = str.split('');
           System.debug('stringCharacters::'+stringCharacters);

        for(integer i=0; i<stringCharacters.size(); i++){
            if(stringCharacters[i].isNumeric()){
                temp = Integer.valueOf(stringCharacters[i]);
                //System.debug('temp::'+temp);
                rem = temp +num;
                //System.debug('rem::'+rem);
                sumOfDigit = math.mod(rem,10);
                //System.debug('sumOfDigit::'+sumOfDigit);
                stringCharacters[i] = sumOfDigit+'';
                //System.debug('ans::'+stringCharacters);
            }

        }
                System.debug('ans::'+stringCharacters);

    }}

and I run the program by giving input:-

Assign2 obj = new Assign2();
 obj.testFunction('2india 234',9); 

help will be appreciable. Thank You.


Solution

  • You've used split with empty string as parameter (meaning you want to cut it into 1-character strings). All you have to do is to reverse the process with join.

    List<String> characters = new List<String>{'1','i','n','d','i','a',' ','1','2','3'};
    String word = String.join(characters, '');
    System.debug(word); // "1india 123"