When we work on strings in Apex, we often take inputs like names, emails, or messages from forms or records. For example, suppose you’re building a custom form where users enter their full name and email.
Before saving this data to Salesforce, you want to ensure everything looks good. You need to check that the fields are not blank, that the name starts with capital letters, and that the email contains ‘@’ to ensure it’s valid.
In this tutorial, we will learn about String class methods in Salesforce Apex to ensure that the data the user is entering matches the criteria.
What are String Class Methods in Salesforce Apex?
In Salesforce Apex, the String class is a built-in class that provides a set of methods (functions) to work with text strings. These methods allow developers to compare, search, format, and analyze string data easily and efficiently.
A String in Apex is simply a sequence of characters, for example, ‘abcd’, ‘john.doe@gmail.com’, or ‘12345’.
String Class Methods and Examples in Salesforce Apex
Below, I will explain the different String class methods and examples and how we can use these methods in Apex code to ensure that the data the user provides matches the criteria.
1. Length() Method in the Apex String Class
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('*************************');
System.debug('Username is valid');
System.debug('*************************');
} else {
System.debug('Username too short');
}
}
}In the above code, we have 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, while creating an Account record, we check that the account name is not empty and should be entered with whitespace.
In the apex class below, we have used the containsWhitespace() method to check whether the account name should be entered with 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, where we checked the whitespace in the string, 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 above code, you can see the email that we provided in the upper and lower case, but the email should be only in lower case, so here we have used the toLowerCase() method in the Apex String class, which converts all characters in a string 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, while creating the record in Salesforce, you want to validate if an email domain is allowed, then only the email address will be accepted.
Let’s say if the user has provided the ‘@salesforce’ domain, then only email is accepted; other domains are 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 above code, you can see that we are using the contains() method to provide the @salesforce.com domain as a substring, so that this method will check if this substring is present in the main string; if it is, it will return true, otherwise 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 provided lower-case letters in the promo code field while 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 above code, you can see the promo code that we provided in lowercase, but the code should be only in uppercase. So, here, we have used the toUpperCase() method in the Apex String class, which converts all characters in a string to uppercase.

Check out: Convert String to Blob in Salesforce Apex
6. split(String regex) Method in the Apex String Class
The split(String regex) method in the Apex String class is used to divide 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 a comma, and you want to store those names separately in the list collection in Salesforce Apex. 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 providing 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, only 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, and the information is not in the proper format. There are some spaces between the first or last letters, and you want to fix those spaces 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 the list collection and provided the account information in the list collection, which we passed to the static method in the Apex class.
After that, to execute the Apex class static method, we directly called that method using the class name without creating the class 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 before and after trimming the account information.
Before, there was whitespace at the beginning and end of a text. But after using the trim() method, there is no space.

8. 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 the match, it removes it and gives you 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 above code, you can see that we have some extra tags in the company name, and we want to remove them. Here, in the remove(substring), we provided the substring that we want to remove from the main string.
While providing the substring, we provided an exact match of the string from the main string and ensured the 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.

9. 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 it will cause an error when the code runs.
This method is helpful when you want to return a specific substring of a string, such as a few characters from an ID, name, or some 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. Now, after extracting the code, the record can 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.

10. 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 gives you a new string with the changes, but the original string 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 and 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 above Apex class, we used the replace() method to change the string. In the method, we need to give two parameter values.
Here, we have {{UserName}}, which is the target value, that means this method will find this string in the original string, and it will be replaced with another string, which is the second parameter.
SO the second parameter we have is replacement, which replaces the target string with a new one.

11. 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.

Conclusion
I hope you have an idea about the String class methods in Salesforce Apex. I have explained different methods and how we can use them in Salesforce Apex code to manipulate the strings to ensure that the data the user enters matches the criteria.
You may like to read:
- Convert a String to Decimal in Salesforce Apex
- Convert String To Lowercase And Uppercase In Salesforce Apex
- addError() Method 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.