Salesforce apex string class and methods with practice examples

String is one of the primitive data type in salesforce. Mastering how to handle strings is key, as they're the building blocks for various data manipulation.

In this guide we will dives into string manipulation in Salesforce Apex, explaining essential string class and methods and showing you how to use them in real-world situations.

String class in apex

The string class in apex is a built-in class that makes it easy for salesforce developers to work with text data.

It provides various methods like substring(), split(), trim(), and replace() to manipulate and handle strings efficiently in custom business logic, validation, and data processing.

The apex string class enables developers to work with text data in custom business logic, validation, and data processing.

How to write a string in Apex

Strings in Salesforce Apex are sequences of characters enclosed within single quotes (' '). They serve as versatile entities for storing and manipulating textual data. Here's a basic example:

String greeting = 'Hello, Decodeforce!';

What are the apex string methods

Salesforce Apex offers a robust set of string manipulation methods. These reusable methods helps developers to efficiently work with strings within their Apex code.

The following are some of the most important string methods available in Salesforce

1. charAt

This function retrieves and returns the integer value of the character at the specified index within the String.

String mainString = 'Salesforce Apex';
Integer charInt = mainString.charAt(3);
System.debug('Character at 3 is: ' + charInt); //Character at 3 is: 101

2. Concatenate strings

Apex does not have a built-in method for concatenation, but combining two strings using the '+' operator will achieve concatenation.

String firstPart = 'Hello';
String secondPart = 'Decodeforce';
String concatenatedString = firstPart + ' ' + secondPart;
System.debug('Concatenated String: ' + concatenatedString); //Concatenated String: Hello Decodeforce

3. Contains

Find if a string contains a specified substring return true else return false.

String mainString = 'Salesforce Apex';
Boolean containsString = mainString.contains('Apex');
System.debug('Contains String: ' + containsString); //Contains String: true

4. equalsIgnoreCase

This method returns true if the secondString is not null and matches first string, disregarding case sensitivity.

String mainString = 'Salesforce Apex';
Boolean equalsString = mainString.equalsIgnoreCase('salesforce apex');
System.debug('Equal String: ' + equalsString); //Equal String: true

5. isAlphanumeric

This method evaluates to true if all characters within the String are letters or numbers; otherwise, it returns false.

String passwordString = 'Salesforce123#';
Boolean isAlphaNumeric = passwordString.isAlphanumeric();
System.debug('isAlphaNumeric: ' + isAlphaNumeric); //isAlphaNumeric: false

6. isBlank

This function return true if the provided string is whitespace, empty (''), or null; otherwise, it return false.

String originalString = ' ';
Boolean isBlank = String.isBlank(originalString);
System.debug('isBlank: ' + isBlank); //isBlank: true

7. Join strings

Joins the elements of a list into a single string using a specified delimiter.

List<String> words = new List<String>{'Hello', 'World', 'from', 'Decodeforce'};
String joinedString = String.join(words, ' ');
System.debug('Joined String: ' + joinedString); //Joined String: Hello World from Decodeforce

8. Length

Find the length of a given string.

String inputString = 'Hello Decodeforce';
System.debug('Length is ' + inputString.length()); //Length is 17

9. left

This function returns the initial characters of the given string up to the specified length.

String inputString = 'Hello Decodeforce';
System.debug('String is ' + inputString.left(5)); //String is Hello

10. Replace

Replaces occurrences of a specified substring/character with another substring in a string.

String originalString = 'Hello, Salesforce';
String replacedString = originalString.replace('Salesforce', 'Decodeforce');
System.debug('Replaced String: ' + replacedString); //Replaced String: Hello, Decodeforce

11. Split

Splits a string into substrings based on a specified delimiter and returns a list of substrings.

String sentence = 'Hello Decodeforce';
List<String> words = sentence.split(' ');
System.debug('Words: ' + words); //Words: (Hello, Decodeforce)

12. StartsWith

Checks if a string starts with a specified prefix.

String mainString = 'Apex is easy to learn';
Boolean startsWith = mainString.startsWith('Apex');
System.debug('Starts with "Apex": ' + startsWith); //Starts with "Apex": true

13. Substring

Extracts a substring from a specified start, end index.

String originalString = 'Hello Decodeforce';
Integer startIndex = 6;
Integer endIndex = 17;
String subString = originalString.substring(startIndex, endIndex);
System.debug('SubString: ' + subString); //SubString: Decodeforce

14. toLowerCase

Converts all characters in a string to lowercase.

String originalString = 'Decodeforce Apex';
String lowerCaseString = originalString.toLowerCase();
System.debug('Lowercase String: ' + lowerCaseString); //Lowercase String: decodeforce apex

15. toUpperCase

Converts all characters in a string to uppercase.

String originalString = 'Apex';
String upperCaseString = originalString.toUpperCase();
System.debug('Uppercase String: ' + upperCaseString); //Uppercase String: APEX

16. trim

Remove all leading and trailing spaces from a given string.

String originalString = '     Apex  ';
String modifiedString = originalString.trim();
System.debug('modifiedString: ' + modifiedString); //modifiedString: Apex

Apex string practice examples

Following are a list of practice examples to learn and use the apex string methods. Click the following button to see all apex practice problems.

Visit all practice problems

Apex method to verify if the given input contains the word 'salesforce'

Write an apex method to check if the given input string contains a keyword using built in apex string methods. Solve this practice example here.

Apex string method to concatenate first, last name

Practice writing an apex method to concatenate two input strings. Solve this practice example here.

Apex method to validate the length of an input string

Apex practice example to validate the length of an input string using apex string methods. Solve this practice example here.

Apex method for validating password requirements

Apex practice method to find length and characters from an input string to validate the password requirements. Solve this practice example here.

Apex string method to mask credit card numbers

Practice apex string methods to find and replace the first three blocks of numbers from a given credit card number with 'x' utilizing the built in apex string methods. Solve this practice example here.

Find the product code from a string

Apex practice method to find the product code from a given string. Utilize apex string methods to find characters from a given input. Solve this practice example here.

Apex string best practices

To harness the full potential of string manipulation in Salesforce Apex, follow these best practices:

1. Null Value Handling

Always verify for null values before string operations to prevent NullPointerExceptions.

2. Method Selection

Choose the appropriate string method based on the task at hand, such as startsWith() and endsWith() for prefix and suffix checks.

Conclusion

String methods are the building blocks of Apex code, and understanding how to use them effectively is crucial. This guide will equip you with the knowledge and practical applications of essential Salesforce Apex string methods, setting you on the path to becoming a proficient developer.