When you start writing Apex code in Salesforce, one thing you will use again and again is the String.
Whether you are working with Names, Emails, Phone Numbers, Addresses, IDs, or Messages — everything is text. And in Apex, text is handled using the String class.
Many beginners think that a string is very simple. They only use it to store text values. But in reality, the Apex String class has many powerful built-in methods that can reduce your code and make your logic very easy.
If you don’t know these methods, you may end up writing long logic, loops, and conditions that are not required at all.
In this article, you will learn the most important String class in Apex Salesforce with different methods, simple examples, and real-time use cases. After reading this, you will start using these methods naturally in your Apex programs.
What is a String in Salesforce Apex?
A string is just text. Simple as that. A String is a sequence of characters enclosed in single quotes.
String Name = 'John';
String email = 'john.doe@example.com';
String message = 'Hello, this is a test message!';In Apex, strings are immutable. That means once you create a string, you can’t change it. Every time you “modify” a string, you’re actually creating a new one.
Keep this in mind when you’re working with lots of string operations – it can affect performance.
Create Strings in Salesforce Apex
There are several ways to create strings in Apex:
Direct assignment:
String name = 'Sarah Connor';Using the String constructor:
String name = String.valueOf('Sarah Connor');Empty strings:
String emptyString = '';
String anotherEmpty = String.valueOf('');Most of the time, you’ll just use the direct assignment. It’s cleaner and easier to read.
Different Methods of the String Class in Apex Salesforce
Below, I will explain the String class methods and examples, and how we can use them in Apex code.
1. length() Method in Apex String
The length() method in the Apex String class returns the number of characters in a string, including spaces and special characters.
This method is very useful for validation, such as checking if a string exceeds a specific limit.
For example, we want to check if a username meets a minimum length requirement. If it does not, we need to display an error message stating that the username cannot exceed 60 characters.
public class StringMethods {
public void stringMethod(){
String username = 'sf_dev_123';
if(username.length() >= 8) {
System.debug('Username is valid');
} else {
System.debug('Username too short');
}
}
}In the code above, we used a string.length() function to check the number of characters available in the string.

2. containsWhitespace() Method in the Apex String Class
Now, what if we want space between two letters in the string? For that, we have another String class method. Let’s understand how we can use it in Apex code in Salesforce.
The containsWhitespace() method in the String class checks if a string contains any whitespace characters, such as spaces, tabs, newlines, etc., and returns a Boolean value.
For example, when creating an Account record, we check that the account name is not empty and that it is entered with leading or trailing whitespace.
In the apex class below, we use the containsWhitespace() method to determine whether the account name should include whitespace. We have also used exception handling to handle the error.
public with sharing class StringMethods {
public void checkStringMethod (Account acc) {
if (acc.Name == null) {
throw new CustomException (' Account Name cannot be empty.');
}
if (!acc.Name.containsWhitespace()) {
throw new CustomException (' Enter Full Name and it Should contain spaces.');
}
try {
upsert acc;
System.debug (' Account saved successfully: ' + acc.Name);
} catch (DmlException e) {
System.debug ( 'Error while saving Account: ' + e.getMessage());
throw e;
}
}
public class CustomException extends Exception {}
}To execute the class, we need to create an Account instance and provide the account name. First, I entered the account name correctly, which contains whitespace. Then, I executed the code, and you can see the record was saved successfully.

Now, I entered the account name without any whitespace between the two strings and then executed the code. We got an exception that we declared in the if condition, which checked the string’s whitespace, and the record was not saved.

3. toLowerCase() Method in the Apex String Class
The toLowerCase() method in the Apex String class converts all characters in a string to lowercase and returns the modified string.
It does not change the original string, as strings in Apex are immutable. It is very useful for case-insensitive comparisons or standardizing user input.
For example, the user provided capital letters in the email field while filling out the form, so you want to store it in lowercase. For that, we can use the toLowerCase() method.
public class StringMethods {
public void stringMethod() {
String emailInput = 'AlexAnderson@Gmail.COM';
String normalizedEmail = emailInput.toLowerCase();
System.debug(normalizedEmail);
}
}In the code above, you can see the email provided in both upper and lowercase; it should be lowercase only. We used the toLowerCase() method in the Apex String class to convert all characters to lowercase.

4. contains(String substring) Method in the Apex String Class
The contains(String substring) method in the Apex String class checks whether a given substring exists within the main string. It returns a Boolean value: true if the substring is found, and false if not.
The search is case-sensitive, meaning “Hello”.contains(“he”) returns false. This method validates input or checks for specific keywords in a string.
For example, when creating a record in Salesforce, you want to validate whether an email domain is allowed; only then will the email address be accepted.
Let’s say that if the user has provided the ‘@salesforce’ domain, only email from that domain is accepted; email from other domains is not accepted.
public class StringMethods {
public void stringMethod() {
String email = 'user@salesforce.com';
if(email.contains('@salesforce.com')) {
System.debug(email + ' Allowed Domain');
} else {
System.debug(email + ' Not Allowd Domain');
}
}
}In the code above, we use the contains() method to check whether the @salesforce.com domain is a substring of the main string; if it is, it returns true; otherwise, it returns false.

In the image below, you can see that we provided Gmail with the .com domain, but it displayed a “Not Allowed Domain” message.

5. toUpperCase() Method in the Apex String Class
The toUpperCase() method in the Apex String class converts all characters in a string to uppercase and returns the modified string.
It does not change the original string, as strings in Apex are immutable. It is very useful for case-insensitive comparisons or standardizing user input.
For example, the user entered lowercase letters in the promo code field when filling out the form, so you want to store it in uppercase. For that, we can use the toUpperCase() method.
public class StringMethods {
public void stringMethod() {
String promoCode = 'save20';
String code = promoCode.toUpperCase();
System.debug(code);
}
}In the code above, you can see the promo code we provided in lowercase, but it should be in uppercase. So, here, we have used the toUpperCase() method in the Apex String class, which converts all characters in a string to uppercase.

6. split(String regex) Method in the Apex String Class
The split(String regex) method in the Apex String class splits a string into an array of substrings based on a character or sequence of characters used to separate the string.
It returns a List<String> containing the split parts. It is useful when you want to break a string using specific characters or patterns, such as commas, spaces, or special symbols.
For example, you have multiple contact names separated by commas and want to store them separately in a Salesforce Apex list collection. For that, we can use the split() method.
public class StringMethods {
public void stringMethod() {
String contactNames = 'Alice, Bob, Charlie';
List<String> nameList = contactNames.split(',');
for (String name : nameList) {
System.debug('Contact Name: ' + name);
}
}
}In the above Apex code, we have a string containing the contact names, and we defined a list collection to store the separate contact names.
Then, using the split() method and a regex character, we separated the string by a comma (,).

7. trim() Method in the Apex String Class
The trim() method in Apex removes extra spaces at the beginning and end of a text. It doesn’t change the spaces between words; it only changes the spaces before the first word and after the last word.
This is helpful when working with data that might have unwanted spaces, such as user input or values from other systems.
For example, you have a list of account information that is not in the proper format. There are spaces between the first and last letters; fix them and save the list in the proper format.
public class StringMethods {
public static List<Account> cleanAccountData(List<Account> externalAccounts) {
for (Account acc : externalAccounts) {
System.debug('Before Trim - Name: "' + acc.Name + '", Website: "' + acc.Website + '"');
if (acc.Name != null) {
acc.Name = acc.Name.trim();
}
if (acc.Website != null) {
acc.Website = acc.Website.trim();
}
System.debug('After Trim - Name: "' + acc.Name + '", Website: "' + acc.Website + '"');
}
return externalAccounts;
}
}Here, I created a list collection and added the account information to it, which we then passed to the static method in the Apex class.
After that, to execute the Apex class’s static method, we called it directly using the class name, without creating an instance.
List<Account> testAccounts = new List<Account>{
new Account(Name = ' ABC Corp ', Website = ' www.abccorp.com '),
new Account(Name = ' XYZ Ltd ', Website = 'www.xyz.com ')
};
StringMethods.cleanAccountData(testAccounts);You can see the output below; I have displayed the account information before and after trimming.
Before, there was whitespace at the beginning and end of a text. But after using the trim() method, there is no space.

8. startsWith() and endsWith() – Check Beginning or End
String fileName = 'report.pdf';
if(fileName.endsWith('.pdf')) {
// Process PDF file
}
String phoneNumber = '+1-555-1234';
if(phoneNumber.startsWith('+1')) {
// US number
}These are also case-sensitive. Really handy for file type checking or prefix validation.
9. remove(substring) Method in the Apex String Class
The remove(substring) method in Apex removes the first matching part of the text you give it from the original string.
Also, it is case-sensitive, so it looks for an exact match (uppercase and lowercase). If it finds a match, it removes it and returns the new string. If it doesn’t find the match, it returns the original string.
For example, in the lead record, you store the company name as “Acme Inc. – Partner” in the company field. But for integration purposes, you want to remove the tag “ – Partner” before sending it to a third-party system.
public class StringMethods {
public void stringMethod(){
String companyName = 'Acme Inc. - Partner';
String cleanedCompanyName = companyName.remove(' - Partner');
System.debug(' ' +cleanedCompanyName);
}
}In the code above, you can see that we have extra tags in the company name, and we want to remove them. Here, in the remove(substring) method, we provided the substring we want to remove from the main string.
While providing the substring, we ensured an exact match within the main string and maintained case sensitivity.

Now, this time, we provided an in-case-sensitive substring, and you can see the output. If it doesn’t find a match, it returns the original string.

10. substring(startIndex, endIndex) Method in the Apex String Class
In Salesforce Apex, the substring(startIndex, endIndex) method is used to get a substring of a string. It starts at the position you give in startIndex and stops just before the position in endIndex.
In a string, the first character starts at position 0. It does not change the original string. Then, both numbers (startIndex and endIndex) must be within the string’s length, or the code will throw an error when it runs.
This method is helpful when you want to return a specific substring from a string, such as a few characters from an ID, a name, or a piece of custom code.
For example, in a Salesforce org, a custom field stores a product code like ‘PROD-INV-2025‘ where the prefix indicates the product type. After extracting the code, the record can now be automatically routed to the teams for processing.
public class StringMethods {
public void stringMethod(){
String productCode = 'PROD-INV-2025';
String category = productCode.substring(0, 4);
System.debug('Product Category: ' + category);
}
}In the above Apex class, we have the product code, and we have given the startIndex and endIndex integer values in the substring(0, 4) method to extract the substring.
Here, we have extracted values within the string’s length, so we can see the extracted value in the output.

Now, in this, you can see we provided the startIndex and endIndex integer values in the substring(7, 15), which are not within the string’s length, and it causes an error when we run the code.

11. isEmpty() and isBlank() – Check for Empty Values
String name = '';
Boolean empty = name.isEmpty(); // true
String whitespace = ' ';
Boolean blank = whitespace.isBlank(); // true
Boolean empty2 = whitespace.isEmpty(); // falseHere’s the difference: isEmpty() only checks whether the string is empty. isBlank() also returns true if the string only contains whitespace. In most cases, what you want is isBlank().
12. valueOf() – Convert Other Types to String
Integer count = 42;
String countText = String.valueOf(count); // '42'
Date today = Date.today();
String dateText = String.valueOf(today); // '2026-02-09'
Boolean isActive = true;
String activeText = String.valueOf(isActive); // 'true'This works with pretty much any data type. Really useful when you’re building dynamic messages or concatenating different types.
13. format() – Create Formatted Strings
String template = 'Hello {0}, you have {1} new messages.';
String message = String.format(template, new List<String>{'John', '5'});
// 'Hello John, you have 5 new messages.'The {0}, {1}, etc., are placeholders that get replaced by the values in the list. Much cleaner than a bunch of concatenation.
14. replace(target, replacement) Method in the Apex String Class
The replace(target, replacement) method in the Apex String class is used to find a string that matches a specific word or text (called the target) and replace it with the new string (called the replacement).
It returns a new string with the changes, while the original stays the same. This method is case-sensitive, which means it will only replace text that exactly matches the target, including uppercase and lowercase letters.
For example, you are sending an email from Apex using a template where {{UserName}} is a placeholder that should be replaced with the actual user’s name.
public class StringMethods {
public void stringMethod(){
String emailBody = 'Hello {{UserName}}, your case has been created successfully.';
String actualUserName = 'Alex Anderson';
emailBody = emailBody.replace('{{UserName}}', actualUserName);
System.debug(emailBody);
}
}In the Apex class above, we used the replace() method to modify the string. In the method, we need to give two parameter values.
Here, we have {{UserName}}, which is the target value; this means the method will find this string in the original string and replace it with the second parameter.
SO the second parameter we have is replacement, which replaces the target string with a new one.

15. reverse() Method in the Apex String Class
The reverse() method in Salesforce Apex takes a string and makes a new string with the letters in the reverse order. It does not change the original string.
This is helpful when you want to work with the string backwards, like checking if a word is the same forwards and backwards (a palindrome) or changing the format.
For example, you want to check if a case number (e.g., “CASE1234”) has a specific pattern when reversed, or you need to log the reversed case number for debugging.
public class StringMethods {
public void stringMethod(){
String caseNumber = 'CASE1234';
String reversedCaseNumber = caseNumber.reverse();
System.debug('Reversed Case Number: ' + reversedCaseNumber);
}
}In the below output, you can see the reverse string that we got using the reverse() method in the String class.

Common Mistakes to Avoid in String Class in Salesforce Apex
1. Forgetting that strings are case-sensitive
String status = 'Active';
if(status == 'active') { // This is false!
// Won't execute
}
// Do this instead:
if(status.equalsIgnoreCase('active')) {
// Will execute
}2. Not checking for null or blank
String email; // This is null
Integer len = email.length(); // NullPointerException!
// Always check first:
if(String.isNotBlank(email)) {
Integer len = email.length();
}3. Using too many string concatenations in loops
// Bad - creates a new string every iteration
String result = '';
for(Integer i = 0; i < 1000; i++) {
result += 'Line ' + i + '\n';
}
// Better - use a list and join
List<String> lines = new List<String>();
for(Integer i = 0; i < 1000; i++) {
lines.add('Line ' + i);
}
String result = String.join(lines, '\n');Conclusion
I hope you have an idea of the most important String class in Salesforce Apex, with different methods, simple examples, and real-world use cases. After reading this, you will start using these methods naturally in your Apex programs.
I have explained different methods and how to use them in Salesforce Apex code to manipulate strings and ensure that the user-entered data matches the criteria.
You may like to read:
- addError() Method in Salesforce Apex
- Convert a String to Decimal in Salesforce Apex
- Convert String To Lowercase And Uppercase In Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.