Data Types, Strings, Dates and Operators · Lesson 5 of 41
Apex String Methods with Examples
Strings are everywhere in Salesforce code: names, emails, phone numbers, external Ids, JSON, error messages. The String class has dozens of methods; this lesson focuses on the ones you'll use every week, grouped by job, plus two behaviours that catch out developers coming from Java.
In this lesson
- Comparing strings (== is case-insensitive!)
- Checking for empty values
- Searching, extracting and replacing
- Splitting, joining and formatting
- Building strings efficiently
Comparing strings
String a = 'Acme';
String b = 'ACME';
System.debug('a == b: ' + (a == b)); // case-insensitive!
System.debug('a.equals(b): ' + a.equals(b)); // case-sensitive
System.debug('equalsIgnoreCase: ' + a.equalsIgnoreCase(b));
System.debug('compareTo: ' + 'apple'.compareTo('banana')); // negative: comes first
// sets and map keys ARE case-sensitive
Set<String> names = new Set<String>{ 'Acme' };
System.debug('set contains ACME? ' + names.contains('ACME'));
a == b: true a.equals(b): false equalsIgnoreCase: true compareTo: -1 set contains ACME? false
== ignores case, Set and Map don't
In Apex, 'Acme' == 'ACME' is true, but a Set<String> or Map<String, …> treats them as different keys. When matching user input or external data against a set, normalise first: key.toLowerCase().
Checking for empty values
String nothing = null;
String empty = '';
String spaces = ' ';
System.debug('isBlank: ' + String.isBlank(nothing) + ' ' + String.isBlank(empty) + ' ' + String.isBlank(spaces));
System.debug('isEmpty: ' + String.isEmpty(nothing) + ' ' + String.isEmpty(empty) + ' ' + String.isEmpty(spaces));
System.debug('isNotBlank: ' + String.isNotBlank('Acme'));
// the static methods are null-safe; instance methods on null throw
try {
Integer len = nothing.length();
} catch (NullPointerException e) {
System.debug('NullPointerException on nothing.length()');
}
System.debug('Default: ' + (String.isBlank(nothing) ? 'N/A' : nothing));
isBlank: true true true isEmpty: true true false isNotBlank: true NullPointerException on nothing.length() Default: N/A
Use String.isBlank() for validation – it treats null, empty and whitespace-only the same, which is almost always what you want for user input.
Searching, extracting and replacing
String email = ' Ravi.Kumar@Example.COM ';
String clean = email.trim().toLowerCase();
System.debug(clean);
System.debug('contains @: ' + clean.contains('@'));
System.debug('domain: ' + clean.substringAfter('@'));
System.debug('user: ' + clean.substringBefore('@'));
System.debug('ends with .com: ' + clean.endsWith('.com'));
System.debug('index of dot: ' + clean.indexOf('.'));
String invoice = 'INV-2026-00042';
System.debug('year: ' + invoice.substring(4, 8));
System.debug('last 5: ' + invoice.right(5) + ', first 3: ' + invoice.left(3));
System.debug('number: ' + Integer.valueOf(invoice.substringAfterLast('-')));
String phone = '+91 (98765) 43210';
System.debug('digits only: ' + phone.replaceAll('[^0-9]', ''));
System.debug(invoice.replace('INV', 'CRN'));
ravi.kumar@example.com contains @: true domain: example.com user: ravi.kumar ends with .com: true index of dot: 4 year: 2026 last 5: 00042, first 3: INV number: 42 digits only: 919876543210 CRN-2026-00042
replace works on plain text; replaceAll and split take a regular expression, so characters like ., | and + have special meaning – which leads to the next gotcha.
Splitting, joining and formatting
String tags = 'apex, soql , dml,,triggers';
List<String> parts = new List<String>();
for (String t : tags.split(',')) {
if (String.isNotBlank(t)) parts.add(t.trim());
}
System.debug(parts);
System.debug(String.join(parts, ' | '));
// split takes a regex: escape special characters
System.debug('split on "." gives ' + 'v1.2.3'.split('.').size() + ' parts (regex: any character)');
System.debug('escaped dot gives ' + 'v1.2.3'.split('\\.').size() + ' parts');
// String.format fills numbered placeholders
String msg = String.format('Hi {0}, your case {1} is {2}.', new List<Object>{ 'Neha', '00001042', 'Closed' });
System.debug(msg);
System.debug('acme corp'.capitalize() + ' | ' + 'Long description text'.abbreviate(12));
System.debug('7'.leftPad(4, '0') + ' | ' + 'abc'.reverse() + ' | ' + 'na'.repeat(3));
System.debug(' too many spaces '.normalizeSpace());
(apex, soql, dml, triggers) apex | soql | dml | triggers split on "." gives 0 parts (regex: any character) escaped dot gives 3 parts Hi Neha, your case 00001042 is Closed. Acme corp | Long desc... 0007 | cba | nanana too many spaces
Building long strings
Strings are immutable: every += creates a new String. For a few pieces that's fine; for thousands of lines (a CSV export) collect parts in a list and join once – it's faster and uses less heap:
List<String> rows = new List<String>{ 'Name,Industry' };
for (Integer i = 1; i <= 3; i++) {
rows.add('Account ' + i + ',Technology');
}
String csv = String.join(rows, '\n');
System.debug(csv);
System.debug('Length: ' + csv.length());
Name,Industry Account 1,Technology Account 2,Technology Account 3,Technology Length: 76
Escaping
- Inside a string literal, escape a single quote as
\'and a backslash as\\;\nis a newline. - Never build SOQL from user input by concatenation. Use bind variables – or at least
String.escapeSingleQuotes(input)(see dynamic SOQL). escapeHtml4(),escapeCsv()andescapeEcmaScript()exist for output in those formats.
Practice
Try it yourself
Write a method that turns " asha VERMA " into "Asha Verma".
Show answer
List<String> out = new List<String>(); for (String p : name.normalizeSpace().toLowerCase().split(' ')) { out.add(p.capitalize()); } return String.join(out, ' ');A Set of existing emails contains 'asha@acme.com'. Why does
emails.contains('Asha@Acme.com')return false, and how do you fix it?Show answer
Set lookups are case-sensitive. Store and look up normalised values: add
email.toLowerCase()and checkcontains(input.toLowerCase()).
Quick check
Is 'abc' == 'ABC' true in Apex?
Yes – == on Strings is case-insensitive. Use equals() for a case-sensitive check.
Which method treats null, '' and ' ' as empty?
String.isBlank().
Why does split('.') not split on dots?
split takes a regex, and . matches any character; use split('\\.').
Summary
- == is case-insensitive; equals() is not; Set and Map keys are case-sensitive.
- Validate with String.isBlank(), which is null-safe.
- split and replaceAll take regular expressions – escape special characters.
- Use String.format for messages and List + String.join for long strings.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.