ApexSensei

Drills › Write Apex

Split and join text

Write Apex · Beginner · 12 min · Runs in your Salesforce Developer org · Free

Scenario. A multi-select picklist stores values with semicolons, but the sales summary shows them with commas.

Split a multi-select picklist value into a List, add a value, join it for display, and split on dots safely.

What you will learn

split cuts text into a List<String>. A List is a growable array; here you need .size() to count, .add(x) to append, and list[0] to read.

List<String> items = 'Gold;Silver'.split(';');
items.add('Bronze');
System.debug(items.size()); // 3
System.debug(String.join(items, ', '));

Gotcha. split reads its argument as a pattern. split('.') gives an empty list; split('|') cuts between every character. Escape them: split('\\.') and split('\\|').

The task

Turn a multi-select picklist value into a List, add one value, and join it for display. Then split a My Domain host on its dots.

Examples:

  • Enterprise;Renewal;EMEA plus Upsell → Count: 4 and Display: Enterprise, Renewal, EMEA, Upsell
  • Renewal → Single count: 1 and Single display: Renewal
  • acme.my.salesforce.com → Host parts: 4

Requirements:

  1. Split source on ; and add Upsell to the List.
  2. Join the List with String.join and ', ' (a comma and a space). Print Count: and Display: from the List.
  3. Split the single value Renewal the same way, then print Single count: and Single display: from the new List.
  4. Split host on its dots with an escaped dot, '\\.', and print Host parts: with the List size.

Starter code

String source = 'Enterprise;Renewal;EMEA';
List<String> parts;

// Case A: split the picklist value and add Upsell

// Case B: a single picklist value
source = 'Renewal';

// Case C: split a My Domain host on its dots
String host = 'acme.my.salesforce.com';

When it passes

The picklist value becomes 4 items shown with commas, the single value stays one item, and the host splits into 4 parts.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Parse an email · Working with dates ›