Salesforce | Split function on some special characters like (.) does not work in apex

|
| By Webner

Description: Using a Split function over some special characters like ‘.’ is bit ambiguous, As Apex does not recognise these characters to be part of the splitting string.

For Example: //this will fail reporting a size of 0

string s = 'first.second';
string[] part;
part = s.split('.');
System.DEBUG(part.size());

Solution: To overcome such problem in Apex, one should use some regex character like” \\” before the splitting character. It will throw Index out of bound error. So you should use the code as:

string s = 'first.second';
string[] part;
part = s.split('\\.')[1];
System.DEBUG(‘first character is: ’+part);

Output: First character is: first

Leave a Reply

Your email address will not be published. Required fields are marked *