How To Split String Method In Salesforce Apex?

4.8K    Asked by AlGerman in Salesforce , Asked on Nov 18, 2022

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 a split it will return 'this' in zero indexes and rest in the first index.

It is used to break your apex string split. Showing an example below with a small case about it. Maybe this can help you.


Example:

Let suppose you are getting something like address(F-206, Daffodils, Magarpatta, Pune, India, 411028) in one text field and you want to store this address in different segments like house no, Building name, Street, City, Country. for this you can use split function for this by given code. 
String addressFull = 'F-206, Daffodils, Magarpatta, Pune, India, 411028';
String[] address = addressFull.split(',');
String houseNumber = address[0];
String buildingName = address[1];
String streetName = address[2];
String cityName = address[3];
String countryName = address[4];
System.debug(houseNumber);
System.debug(buildingName);
System.debug(streetName);
System.debug(cityName);
System.debug(countryName);
Output: please check debug logs after that, you will be able to see

Your Answer

Answer (1)

In Salesforce Apex, you can split a string into substrings using the split() method. Here's how you can use it:

String myString = 'Hello,World,How,Are,You';
// Split the string using a delimiter (comma in this case)
List parts = myString.split(',');
In this example:

myString is the original string you want to split.

split(',') splits the string using the comma , as the delimiter.

The result is stored in a List called parts, where each element represents a substring.

You can replace ',' with any other character or string you want to use as a delimiter. For example, to split by space, you would use split(' ').


Keep in mind that the split() method is case-sensitive. If you want case-insensitive splitting, you might need to preprocess the string or use regular expressions with appropriate flags.// Iterate through the parts

for(String part : parts) {
    System.debug(part);
}
7 Months

Interviews

Parent Categories