Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How to Split string method in salesforce Apex?

Asked by James Scott Aug 17, 2021 8.8K views 2 answers
Share

About this question

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.

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on May 16, 2024

In Salesforce Apex, you can split a string into an array of substrings using the split() method available on the String class. This method takes a delimiter as an argument and returns an array of strings.


Here's an example of how you can use the split() method:

String originalString = 'apple,banana,orange';
List splitStrings = originalString.split(',');

In this example, the original string "apple,banana,orange" is split into substrings based on the delimiter ",", resulting in an array splitStrings containing three elements: "apple", "banana", and "orange".

You can adjust the delimiter according to your specific use case. If you want to split based on a different delimiter, simply replace ',' with the desired delimiter.

Keep in mind that if the delimiter is not found in the original string, the split() method will return an array containing the original string as the only element.

Here's an example:

String originalString = 'apple-banana-orange';
List splitStrings = originalString.split(',');

In this case, since the delimiter ',' is not found in the original string, the split() method will return an array containing the original string "apple-banana-orange" as the only element in splitStrings.

Remember to handle any potential exceptions that may occur, such as NullPointerException if the original string is null.


Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.