String Class Functions in Apex: A Complete Guide

Formulas & functions · Updated November 23, 2026

In Apex, the String class provides over 80 built-in methods for manipulating text, including case conversion, substring extraction, searching, splitting, and formatting. This article explains the most commonly used String functions with syntax examples, practical use cases, and answers to frequent questions.

Background: Why the String Class Matters in Apex

Apex is a strongly typed, object-oriented language used on the Salesforce platform. Strings are one of the most frequently used data types because they hold record IDs, names, API fields, user input, and JSON payloads. The String class is part of the System namespace, so you don’t need to import anything. Unlike Java, Apex treats strings as primitives with a class wrapper—both String and String (case-insensitive) are valid. Because Salesforce transactions have governor limits, knowing the right String method can save CPU time and avoid hitting limits.

How String Functions Work: Core Methods and Syntax

All String methods are instance methods—you call them on a string variable. They return a new string or a primitive value; they never modify the original string (strings are immutable). Here are the most essential categories:

  • Case conversion: toLowerCase(), toUpperCase(), capitalize()
  • Substring extraction: substring(startIndex), substring(startIndex, endIndex), left(n), right(n)
  • Searching: indexOf(substring), lastIndexOf(substring), contains(substring), startsWith(prefix), endsWith(suffix)
  • Splitting and joining: split(delimiter), join(list) (static method)
  • Trimming and padding: trim(), removeStart(prefix), removeEnd(suffix), leftPad(n), rightPad(n)
  • Replacement: replace(old, new), replaceAll(regex, replacement), replaceFirst(regex, replacement)
  • Formatting: format(listOfArguments), escapeHtml4(), escapeEcmaScript()
  • Validation: isBlank(), isNotBlank(), isAlpha(), isNumeric(), isWhitespace()

Example: String name = 'Salesforce'; then name.substring(0,5) returns 'Sales'.

Practical Examples: Using String Functions in Real Code

Here are three common scenarios with code snippets:

  1. Extracting a field from a CSV line: String csvLine = 'John,Doe,30'; List<String> parts = csvLine.split(','); returns ['John','Doe','30'].
  2. Cleaning user input: String input = ' Hello World '; String cleaned = input.trim(); gives 'Hello World'.
  3. Building a dynamic SOQL query safely: Use String.escapeSingleQuotes(userInput) to prevent injection. Example: String safeName = String.escapeSingleQuotes(name); then String query = 'SELECT Id FROM Account WHERE Name = \'' + safeName + '\'';.

How to Choose the Right String Method

Choosing the correct method depends on what you need to do:

  • If you need to check if a string contains a substring, use contains() instead of indexOf()—it returns a Boolean and is more readable.
  • If you need to split on a regex pattern, use split(); for a literal delimiter, consider splitWithCharacter() (available in Apex) which is faster.
  • If you need to remove a prefix only once, use removeStart(); if you need to remove all occurrences, use replace().
  • For case-insensitive comparisons, use equalsIgnoreCase() rather than converting with toLowerCase()—it’s clearer and avoids creating extra strings.

Common Problems and Pitfalls

Many developers run into these issues:

  • IndexOutOfBoundsException: Using substring() with an end index greater than the string length. Always check length() first.
  • Null pointer: Calling methods on a null string. Use String.isBlank() to check before manipulation.
  • Regex special characters: When using split() or replaceAll(), remember that the first argument is a regex. To treat it literally, escape with Pattern.quote().
  • Governor limits: Excessive string concatenation in loops can consume heap. Use String.join() or a StringBuilder (via StringBuffer class) for large loops.

Comparison: String Methods vs. Other Approaches

Sometimes you might consider using String methods versus other Apex features:

  • String vs. List<String>: If you need to manipulate individual characters frequently, converting to a list of characters is inefficient; stick to substring and indexOf.
  • String methods vs. regular expressions: For complex patterns, use Pattern and Matcher classes instead of replaceAll() to avoid repeated compilation.
  • String vs. Blob: For binary data, use Blob; String is only for text.

Performance and Best Practices

To write efficient Apex string code:

  • Use String.join() to combine a list of strings—it’s faster than looping with +=.
  • Use String.isBlank() instead of == null || == ''.
  • Cache regex patterns in a static variable if you use them repeatedly.
  • Avoid calling toLowerCase() multiple times on the same string; store the result.
  • Remember that strings are immutable; each method call creates a new object, so minimize chaining in loops.

Frequently Asked Questions

What is the difference between contains() and indexOf()?

contains() returns a Boolean indicating whether the substring exists, while indexOf() returns the integer index of the first occurrence, or -1 if not found. Use contains() for simple existence checks; use indexOf() when you need the position to extract further.

How do I split a string by comma but ignore commas inside quotes?

The built-in split() does not handle quoted delimiters. You need to write a custom parser or use a regex like Pattern.compile('(?:\"([^\"]*)\"|([^,]+))') to match quoted sections. Alternatively, consider using the CSVParser class from the System namespace (available in Apex) for robust CSV parsing.

Can I use String.format() with named placeholders?

No, String.format() only supports positional arguments with {0}, {1}, etc. For named placeholders, you must manually replace or use a Map and a loop.

How do I convert a String to an Integer safely?

Use Integer.valueOf(string) but wrap it in a try-catch to handle TypeException. For non-numeric strings, consider using String.isNumeric() first, but note that it returns true for decimals, so validate accordingly.

What is the maximum length of a String in Apex?

Apex strings can hold up to 6,000,000 characters, but Salesforce heap limits (typically 6 MB for synchronous transactions) will be hit much sooner. For large text, consider using the Blob type or storing in a Long Text Area field.

Alternatives and Related Classes

If you need advanced text processing, consider these Apex classes:

  • Pattern and Matcher: For complex regular expressions with groups and repeated matches.
  • StringBuffer: For efficient concatenation in loops (though String.join is often simpler).
  • Blob: For binary data or encoding/decoding with EncodingUtil.
  • JSON and XML classes: For structured data, use JSON.serialize() and JSON.deserialize() rather than manual string parsing.

Understanding these functions will help you write cleaner, more efficient Apex code. Always test edge cases like null, empty, and very long strings to avoid runtime exceptions.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.