How to Split string method in salesforce Apex?

5.9K    Asked by JamesSCOTT in Salesforce , Asked on Aug 17, 2021

Need to split a string by the first occurrence of a specific character like '-' in 'this-is-test-data'. so what i want is when I do split it will return 'this' in zero indexes and rest in first index.

Answered by Kaalappan shingh

Use String.split(regExp, limit) method:

Documentation says

Returns a list that contains each substring of the String that is terminated by either the regular expression regExp or the end of the String.

Example:

    String str = 'this-is-test-data'; List res = str.split('-', 2); System.debug(res);

Result:

    15:16:58:001 USER_DEBUG [3]|DEBUG|(this, is-test-data)

Here we have Splitting String string methods salesforce:

Splitting String Example in Salesforce Apex Class:

    Ex:1. string s = 'first. second'; ...

Note: if you are splitting the string using special characters like (.,*, etc) then use a backslash before the special character.

    Ex:2. string sString = 'theblogreaders*salesforce';


Your Answer

Interviews

Parent Categories