Thursday 18 February 2016

How to split a string into a multiple parts from a common character ?

We may need to split a string into multiple parts from common characters to store it in a set which can be used later for comparison. 

I came across one scenario  like ,I was getting some string which was containing three parts separated by ":"  and I had to compare with custom settings record, I was not sure which part of the string will be match with custom settings record. So I split the string and stored in the set.

Below is some sample code:-

String s = 'Another Person : ChildLine Volunteer Administrator : None';
String s2;
set<String> set_string = new set<String>();
while(s.contains(':')){
s2 = s.substring(0,s.indexof(':')+1);
set_string.add(s2.substring(0,s2.length()-1));
s = s.remove(s2);
}
set_string.add(s);
System.debug('Printing---set_string '+set_string);


Keep learning and sharing...

No comments: