How to split an apex string into smaller chunks?

498    Asked by ClaudineTippins in Salesforce , Asked on Mar 2, 2023

 I have a requirement where I need to split a string into a list of substrings with size 2 that is for example,


String = 'ABCDEF J4' and I want the output as
List subStringList = {'AB', 'CD', 'EF','J4'}
I have tried it in javascript with the following :
var chunkStr = function(str, chunkLength) {
    return str.match(new RegExp('[\s\S]{1,' + +chunkLength + '}', 'g'));
}  

I am not sure how to achieve the same in apex. Could someone please point me in the right direction.

Assuming you want no whitespace in your result of apex string...


String s = 'ABCDEF J4';
s = s.deleteWhitespace();
List subStringList = new List();
for(Integer i=0; i{'AB', 'CD', 'EF', 'J4'}, subStringList);

Your Answer

Interviews

Parent Categories