1

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<String> 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. Thanks in advance.

1

1 Answer 1

5

Assuming you want no whitespace in your result...

String s = 'ABCDEF J4';
s = s.deleteWhitespace();
List<String> subStringList = new List<String>();
for(Integer i=0; i<s.length(); i+=2) {
    subStringList.add(s.substring(i, i+2));
}
System.assertEquals(new List<String>{'AB', 'CD', 'EF', 'J4'}, subStringList);

You must log in to answer this question.

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