• Lessons Home
Topics
Community
  1. Lessons
  2. Strings and Dates in Depth
  3. String Methods
  4. Splitting and Joining

      Splitting and Joining

      Splitting and Joining

      A lot of real data arrives as one long string with a separator inside it: a comma separated list of tags, a full name with a space in the middle, a path with slashes. split() breaks that string into a List<String>, and String.join() puts a list back together.

      Splitting

      split() takes the separator and returns a list of the pieces:

      String tags = 'sales,service,marketing';
      List<String> parts = tags.split(',');
      System.debug(parts.size()); // 3
      System.debug(parts[0]); // sales
      

      The separator itself is never included in any of the pieces.

      Joining

      String.join() is a static method. It takes the list first and the separator second:

      List<String> words = new List<String>{ 'red', 'green', 'blue' };
      System.debug(String.join(words, ' | ')); // red | green | blue
      

      The separator goes BETWEEN the items, so three items produce two separators.

      Split Then Join

      Doing both in turn lets you change the separator of a value:

      String csv = 'one,two,three';
      System.debug(String.join(csv.split(','), ' - ')); // one - two - three
      

      Common Mistakes

      split() reads its argument as a regular expression, so characters such as the dot and the pipe have a special meaning there. To split on a literal dot, escape it: split('\\.').

      Calling split() on a null string throws a null pointer exception, so check String.isBlank() first.

      Why This Matters

      Splitting and joining are how text moves in and out of collections. Once the pieces sit in a list you can loop over them, clean them, filter them, and then rebuild whatever shape you need.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In