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:
- Extracting a field from a CSV line:
String csvLine = 'John,Doe,30';List<String> parts = csvLine.split(',');returns['John','Doe','30']. - Cleaning user input:
String input = ' Hello World ';String cleaned = input.trim();gives'Hello World'. - Building a dynamic SOQL query safely: Use
String.escapeSingleQuotes(userInput)to prevent injection. Example:String safeName = String.escapeSingleQuotes(name);thenString 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 ofindexOf()—it returns a Boolean and is more readable. - If you need to split on a regex pattern, use
split(); for a literal delimiter, considersplitWithCharacter()(available in Apex) which is faster. - If you need to remove a prefix only once, use
removeStart(); if you need to remove all occurrences, usereplace(). - For case-insensitive comparisons, use
equalsIgnoreCase()rather than converting withtoLowerCase()—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 checklength()first. - Null pointer: Calling methods on a null string. Use
String.isBlank()to check before manipulation. - Regex special characters: When using
split()orreplaceAll(), remember that the first argument is a regex. To treat it literally, escape withPattern.quote(). - Governor limits: Excessive string concatenation in loops can consume heap. Use
String.join()or aStringBuilder(viaStringBufferclass) 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
PatternandMatcherclasses instead ofreplaceAll()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.joinis often simpler). - Blob: For binary data or encoding/decoding with
EncodingUtil. - JSON and XML classes: For structured data, use
JSON.serialize()andJSON.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
- COUNTIF Formula in Google Sheets: How to Use It
- Random Number 1-30: How to Generate One
- Conditional Format Blank Cells: Easy Excel Guide
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel IF Formula Examples: Tests, Logic, and ErrorsExcel’s IF formula checks whether a condition is true or false and returns one result for each outcome.…
- SPLIT Function in BigQuery: Syntax & ExamplesThe SPLIT function in BigQuery splits a string into an array of substrings based on a delimiter. For…
- Function in Snowflake: Definition, Use & ExamplesIn Snowflake, a function is a reusable piece of SQL logic that takes input parameters, performs a defined…
- Sort a Filtered List in Excel Without Mixing Up RowsTo sort a filtered list in Excel, open the filter arrow in the column you want to sort,…
- String Functions BigQuery: The Essential GuideThe essential string functions in BigQuery are CONCAT, SUBSTR, REPLACE, UPPER, LOWER, TRIM, SPLIT, REGEXP_EXTRACT, and REGEXP_REPLACE, which…
- COUNTIF in Excel Between Two Values: The Right FormulaTo count numbers between two limits in Excel, use COUNTIFS, which applies both limits to the same range.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.