Salesforce Apex has a variety of methods available to manipulate and analyze strings. Here are a few commonly used string methods:
- length(): This method returns the number of characters in the specified string.Example:
String str = 'Hello, World!'; System.debug(str.length()); // Outputs 13
- startsWith(String prefix): This method checks whether the string starts with the specified prefix. Returns true if it does, false otherwise.Example:
String str = 'Hello, World!'; System.debug(str.startsWith('Hello')); // Outputs true
- endsWith(String suffix): This method checks whether the string ends with the specified suffix. Returns true if it does, false otherwise.Example:
String str = 'Hello, World!'; System.debug(str.endsWith('!')); // Outputs true
- substring(Integer startIndex): This method returns a new string that begins at the specified index in the string. The new string includes all the subsequent characters of the original string.Example:
String str = 'Hello, World!'; System.debug(str.substring(7)); // Outputs 'World!'
- substring(Integer startIndex, Integer endIndex): This method returns a new string that begins at the specified startIndex and ends before the endIndex.Example:
String str = 'Hello, World!'; System.debug(str.substring(7, 12)); // Outputs 'World'
- contains(String str): This method checks if the string contains the specified sequence of characters. Returns true if it does, false otherwise.Example:
String str = 'Hello, World!'; System.debug(str.contains('World')); // Outputs true
- replace(String oldStr, String newStr): This method replaces all occurrences of the oldStr in the string with newStr.Example:
String str = 'Hello, World!'; System.debug(str.replace('World', 'Everyone')); // Outputs 'Hello, Everyone!'
- toLowerCase(): This method converts all the characters in the string to lower case.Example:
String str = 'Hello, World!'; System.debug(str.toLowerCase()); // Outputs 'hello, world!'
- toUpperCase(): This method converts all the characters in the string to upper case.Example:
String str = 'Hello, World!'; System.debug(str.toUpperCase()); // Outputs 'HELLO, WORLD!'
- trim(): This method removes any leading or trailing white spaces from the string.Example:
String str = ' Hello, World! '; System.debug(str.trim()); // Outputs 'Hello, World!'
Please note that all the above examples are using System.debug()
to output the results. The actual methods will not print the results but return them. There are more String manipulation methods available on the String class but we just wanted to post a few of the common ones.
Salesforce Apex security best practices
Working with Time in Salesforce Apex
Schedule Apex in Salesforce: A Technical Guide for Developers