10

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

26

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<String> res = str.split('-', 2);
System.debug(res);

Result:

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

12

One option is to use the substringBefore and substringAfter methods.

String delimiter = '-';
String input = 'this-is-test-data';
String firstSplit = input.substringBefore(delimiter); // 'this'
String lastSplits = input.substringAfter(delimiter);  // 'is-test-data'

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.