1

How To Split String by space and store each character or substring in array I have: String - '(1 OR 2) AND 3' I need in this way:

String [] filterLogicSplittedbySpace=new String[]{'(', '1', 'OR', '2', ')', 'AND', '3'};

Please guide.

2

Usage of String.split method doesn't fit your requirements, as you will have '(1' first element and '2)' third element. Use String.splitByCharacterType method.

Splits the current String by character type and returns a list of contiguous character groups of the same type as complete tokens.

This will split and extract correct parts of your string. Brackets are split from numbers

String str = '(1 OR 2) AND 3';
List<String> groupedResult = str.splitByCharacterType();
List<String> filterLogicSplitbySpace= new List<String>();
for(String sequence :groupedResult){
    if(sequence.isAlphanumeric()){
        filterLogicSplitbySpace.add(sequence);
    } else if(String.isNotBlank(sequence)){
        List<String> brakets = sequence.split('');
        for(String bracket :brakets){
            filterLogicSplitbySpace.add(bracket);
        }
    }
}
System.debug(filterLogicSplitbySpace);

Debug result is:

DEBUG|((, 1, OR, 2, ), AND, 3)

this code also works for more complicated conditions, like String str = '((1 OR 2) AND 3) OR 4';

Debug is:

DEBUG|((, (, 1, OR, 2, ), AND, 3, ), OR, 4)

-1

split(' ') method will do the work.

String spl = 'Hello v ivek { } ';
String[] sp2 = spl.split(' ');
System.debug(sp2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.