String Class
Namespace
Usage
For more information on Strings, see String Data Type.
String Methods
The following are methods for String.
abbreviate(maxWidth)
Signature
public String abbreviate(Integer maxWidth)
Parameters
- maxWidth
- Type: Integer
- If maxWidth is less than four, this method throws a run-time exception.
Return Value
Type: String
Example
String s = 'Hello Maximillian';
String s2 = s.abbreviate(8);
System.assertEquals('Hello...', s2);
System.assertEquals(8, s2.length());
abbreviate(maxWidth, offset)
Signature
public String abbreviate(Integer maxWidth, Integer offset)
Parameters
- maxWidth
- Type: Integer
- Note that the offset is not necessarily the leftmost character in the returned String or the first character following the ellipses, but it appears somewhere in the result. Regardless, abbreviate won’t return a String of length greater than maxWidth.If maxWidth is too small, this method throws a run-time exception.
- offset
- Type: Integer
Return Value
Type: String
Example
String s = 'Hello Maximillian';
// Start at M
String s2 = s.abbreviate(9,6);
System.assertEquals('...Max...', s2);
System.assertEquals(9, s2.length());
capitalize()
Signature
public String capitalize()
Return Value
Type: String
Usage
This method is based on the Character.toTitleCase(char) Java method.
Example
String s = 'hello maximillian';
String s2 = s.capitalize();
System.assertEquals('Hello maximillian', s2);
center(size)
Signature
public String center(Integer size)
Parameters
- size
- Type: Integer
Return Value
Type: String
Example
String s = 'hello';
String s2 = s.center(9);
System.assertEquals(
' hello ',
s2);
center(size, paddingString)
Signature
public String center(Integer size, String paddingString)
Return Value
Type: String
Example
String s = 'hello';
String s2 = s.center(9, '-');
System.assertEquals('--hello--', s2);
charAt(index)
Signature
public Integer charAt(Integer index)
Parameters
- index
- Type: Integer
- The index of the character to get the value of.
Usage
The charAt method returns the value of the character pointed to by the specified index. If the index points to the beginning of a surrogate pair (the high-surrogate code point), this method returns only the high-surrogate code point. To return the supplementary code point corresponding to a surrogate pair, call codePointAt instead.
Example
This example gets the value of the first character at index 0.
String str = 'Ω is Omega.';
System.assertEquals(937, str.charAt(0));
This example shows the difference between charAt and codePointAt. The example calls these methods on escaped supplementary Unicode characters. charAt(0) returns the high surrogate value, which corresponds to \uD835. codePointAt(0) returns the value for the entire surrogate pair.
String str = '\uD835\uDD0A';
System.assertEquals(55349, str.charAt(0),
'charAt(0) didn\'t return the high surrogate.');
System.assertEquals(120074, str.codePointAt(0),
'codePointAt(0) didn\'t return the entire two-character supplementary value.');
codePointAt(index)
Signature
public Integer codePointAt(Integer index)
Parameters
- index
- Type: Integer
- The index of the characters (Unicode code units) in the string. The index range is from zero to the string length minus one.
Usage
If the index points to the beginning of a surrogate pair (the high-surrogate code point), and the character value at the following index points to the low-surrogate code point, this method returns the supplementary code point corresponding to this surrogate pair. Otherwise, this method returns the character value at the given index.
For more information on Unicode and surrogate pairs, see The Unicode Consortium.
Example
This example gets the code point value of the first character at index 0, which is the escaped Omega character. Also, the example gets the code point at index 20, which corresponds to the escaped supplementary Unicode characters (a pair of characters). Finally, it verifies that the escaped and unescaped forms of Omega have the same code point values.
The supplementary
characters in this example (\\uD835\\uDD0A) correspond
to mathematical fraktur capital G:
String str = '\u03A9 is Ω (Omega), and \uD835\uDD0A ' +
' is Fraktur Capital G.';
System.assertEquals(937, str.codePointAt(0));
System.assertEquals(120074, str.codePointAt(20));
// Escaped or unescaped forms of the same character have the same code point
System.assertEquals(str.codePointAt(0), str.codePointAt(5));
codePointBefore(index)
Signature
public Integer codePointBefore(Integer index)
Parameters
- index
- Type: Integer
- The index before the Unicode code point that is to be returned. The index range is from one to the string length.
Return Value
Type: Integer
The character or Unicode code point value that occurs before the specified index.
Usage
If the character value at index-1 is the low-surrogate code point, and index-2 is not negative and the character at this index location is the high-surrogate code point, this method returns the supplementary code point corresponding to this surrogate pair. If the character value at index-1 is an unpaired low-surrogate or high-surrogate code point, the surrogate value is returned.
For more information on Unicode and surrogate pairs, see The Unicode Consortium.
Example
This example gets the code point value of the first character (before index 1), which is the escaped Omega character. Also, the example gets the code point at index 20, which corresponds to the escaped supplementary characters (the two characters before index 22).
String str = '\u03A9 is Ω (Omega), and \uD835\uDD0A ' +
' is Fraktur Capital G.';
System.assertEquals(937, str.codePointBefore(1));
System.assertEquals(120074, str.codePointBefore(22));
codePointCount(beginIndex, endIndex)
Signature
public Integer codePointCount(Integer beginIndex, Integer endIndex)
Parameters
Usage
The specified range begins at beginIndex and ends at endIndex—1. Unpaired surrogates within the text range count as one code point each.
Example
This example writes the count of code points in a substring that contains an escaped Unicode character and another substring that contains Unicode supplementary characters, which count as one code point.
String str = '\u03A9 and \uD835\uDD0A characters.';
System.debug('Count of code points for ' + str.substring(0,1)
+ ': ' + str.codePointCount(0,1));
System.debug('Count of code points for ' + str.substring(6,8)
+ ': ' + str.codePointCount(6,8));
// Output:
// Count of code points for Ω: 1
// Count of code points for 𝔊: 1
compareTo(secondString)
Signature
public Integer compareTo(String secondString)
Parameters
- secondString
- Type: String
Return Value
Type: Integer
Usage
The result is:
- A negative Integer if the String that called the method lexicographically precedes secondString
- A positive Integer if the String that called the method lexicographically follows compsecondStringString
- Zero if the Strings are equal
If there is no index position at which the Strings differ, then the shorter String lexicographically precedes the longer String.
Note that this method returns 0 whenever the equals method returns true.
Example
String myString1 = 'abcde';
String myString2 = 'abcd';
Integer result =
myString1.compareTo(myString2);
System.assertEquals(result, 1);
contains(substring)
Signature
public Boolean contains(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Boolean
Example
String myString1 = 'abcde';
String myString2 = 'abcd';
Boolean result =
myString1.contains(myString2);
System.assertEquals(result, true);
containsAny(inputString)
Signature
public Boolean containsAny(String inputString)
Parameters
- inputString
- Type: String
Return Value
Type: Boolean
Example
String s = 'hello';
Boolean b1 = s.containsAny('hx');
Boolean b2 = s.containsAny('x');
System.assertEquals(true, b1);
System.assertEquals(false, b2);
containsIgnoreCase(substring)
Signature
public Boolean containsIgnoreCase(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Boolean
Example
String s = 'hello';
Boolean b = s.containsIgnoreCase('HE');
System.assertEquals(
true,
b);
containsNone(inputString)
Signature
public Boolean containsNone(String inputString)
Parameters
- inputString
- Type: String
- If inputString is an empty string or the current String is empty, this method returns true. If inputString is null, this method returns a run-time exception.
Return Value
Type: Boolean
Example
String s1 = 'abcde';
System.assert(s1.containsNone('fg'));
containsOnly(inputString)
Signature
public Boolean containsOnly(String inputString)
Parameters
- inputString
- Type: String
Return Value
Type: Boolean
Example
String s1 = 'abba';
String s2 = 'abba xyz';
Boolean b1 =
s1.containsOnly('abcd');
System.assertEquals(
true,
b1);
Boolean b2 =
s2.containsOnly('abcd');
System.assertEquals(
false,
b2);
containsWhitespace()
Signature
public Boolean containsWhitespace()
Return Value
Type: Boolean
Example
String s = 'Hello Jane';
System.assert(s.containsWhitespace()); //true
s = 'HelloJane ';
System.assert(s.containsWhitespace()); //true
s = ' HelloJane';
System.assert(s.containsWhitespace()); //true
s = 'HelloJane';
System.assert(!s.containsWhitespace()); //false
countMatches(substring)
Signature
public Integer countMatches(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Example
String s = 'Hello Jane';
System.assertEquals(1, s.countMatches('Hello'));
s = 'Hello Hello';
System.assertEquals(2, s.countMatches('Hello'));
s = 'Hello hello';
System.assertEquals(1, s.countMatches('Hello'));
deleteWhitespace()
Signature
public String deleteWhitespace()
Return Value
Type: String
Example
String s1 = ' Hello Jane ';
String s2 = 'HelloJane';
System.assertEquals(s2, s1.deleteWhitespace());
difference(secondString)
Signature
public String difference(String secondString)
Parameters
- secondString
- Type: String
- If secondString is an empty string, this method returns an empty string.If secondString is null, this method throws a run-time exception.
Return Value
Type: String
Example
String s = 'Hello Jane';
String d1 =
s.difference('Hello Max');
System.assertEquals(
'Max',
d1);
String d2 =
s.difference('Goodbye');
System.assertEquals(
'Goodbye',
d2);
equals(secondString)
Signature
public Boolean equals(String secondString)
Parameters
- secondString
- Type: String
Return Value
Type: Boolean
Usage
This method returns true when the compareTo method returns 0.
Use this method to perform case-sensitive comparisons. In contrast, the == operator performs case-insensitive string comparisons to match Apex semantics.
Example
String myString1 = 'abcde';
String myString2 = 'abcd';
Boolean result = myString1.equals(myString2);
System.assertEquals(result, false);
equals(stringOrId)
Signature
public Boolean equals(Object stringOrId)
Parameters
- stringOrId
- Type: Object
Return Value
Type: Boolean
Usage
If you compare ID values, the lengths of IDs don’t need to be equal. For example, if you compare a 15-character ID string to an object that represents the equivalent 18-character ID value, this method returns true. For more information about 15-character and 18-character IDs, see the ID Data Type.
Use this method to perform case-sensitive comparisons. In contrast, the == operator performs case-insensitive string comparisons to match Apex semantics.
Example
These examples show comparisons between different types of variables with both equal and unequal values. The examples also show how Apex automatically converts certain values before comparing them.
// Compare a string to an object containing a string
Object obj1 = 'abc';
String str = 'abc';
Boolean result1 = str.equals(obj1);
System.assertEquals(true, result1);
// Compare a string to an object containing a number
Integer obj2 = 100;
Boolean result2 = str.equals(obj2);
System.assertEquals(false, result2);
// Compare a string to an ID of the same length.
// 15-character ID
Id idValue15 = '001D000000Ju1zH';
// 15-character ID string value
String stringValue15 = '001D000000Ju1zH';
Boolean result3 = stringValue15.equals(IdValue15);
System.assertEquals(true, result3);
// Compare two equal ID values of different lengths:
// 15-character ID and 18-character ID
Id idValue18 = '001D000000Ju1zHIAR';
Boolean result4 = stringValue15.equals(IdValue18);
System.assertEquals(true, result4);
equalsIgnoreCase(secondString)
Signature
public Boolean equalsIgnoreCase(String secondString)
Parameters
- secondString
- Type: String
Return Value
Type: Boolean
Usage
The String.equalsIgnoreCase() method ignores the locale of the context user. If you want the string comparison to be performed according to the locale, use the == operator instead. The String.equalsIgnoreCase() method typically executes faster than the operator because the method ignores the locale.
Example
String myString1 = 'abcd';
String myString2 = 'ABCD';
Boolean result =
myString1.equalsIgnoreCase(myString2);
System.assertEquals(result, true);
escapeCsv()
Signature
public String escapeCsv()
Return Value
Type: String
Usage
If the String contains a comma, newline or double quote, the returned String is enclosed in double quotes. Also, any double quote characters in the String are escaped with another double quote.
If the String doesn’t contain a comma, newline or double quote, it is returned unchanged.
Example
String s1 = 'Max1, "Max2"';
String s2 = s1.escapeCsv();
System.assertEquals('"Max1, ""Max2"""', s2);
escapeEcmaScript()
Signature
public String escapeEcmaScript()
Return Value
Type: String
Usage
The only difference between Apex strings and EcmaScript strings is that in EcmaScript, a single quote and forward-slash (/) are escaped.
Example
String s1 = '"grade": 3.9/4.0';
String s2 = s1.escapeEcmaScript();
System.debug(s2);
// Output is:
// \"grade\": 3.9\/4.0
System.assertEquals(
'\\"grade\\": 3.9\\/4.0',
s2);
escapeHtml3()
Signature
public String escapeHtml3()
Return Value
Type: String
Example
String s1 =
'"<Black&White>"';
String s2 =
s1.escapeHtml3();
System.debug(s2);
// Output:
// "<Black&
// White>"
escapeHtml4()
Signature
public String escapeHtml4()
Return Value
Type: String
Example
String s1 =
'"<Black&White>"';
String s2 =
s1.escapeHtml4();
System.debug(s2);
// Output:
// "<Black&
// White>"
escapeJava()
Signature
public String escapeJava()
Example
// Input string contains quotation marks
String s = 'Company: "Salesforce.com"';
String escapedStr = s.escapeJava();
// Output string has the quotes escaped
System.assertEquals('Company: \\"Salesforce.com\\"', escapedStr);
escapeSingleQuotes(stringToEscape)
Signature
public static String escapeSingleQuotes(String stringToEscape)
Parameters
- stringToEscape
- Type: String
Return Value
Type: String
Usage
This method is useful when creating a dynamic SOQL statement, to help prevent SOQL injection. For more information on dynamic SOQL, see Dynamic SOQL.
Example
String s = '\'Hello Jason\'';
system.debug(s); // Outputs 'Hello Jason'
String escapedStr = String.escapeSingleQuotes(s);
system.debug(escapedStr); // Outputs \'Hello Jason\'
// In the first string, \ and ' are escaped with a preceding \, so it is equal to escapedStr
system.assertEquals('\\\'Hello Jason\\\'', escapedStr);
escapeUnicode()
Signature
public String escapeUnicode()
Example
String s = 'De onde você é?';
String escapedStr = s.escapeUnicode();
System.assertEquals('De onde voc\\u00EA \\u00E9?', escapedStr);
escapeXml()
Signature
public String escapeXml()
Return Value
Type: String
Usage
Supports only the five basic XML entities (gt, lt, quot, amp, apos). Does not support DTDs or external entities. Unicode characters greater than 0x7f are not escaped.
Example
String s1 =
'"<Black&White>"';
String s2 =
s1.escapeXml();
System.debug(s2);
// Output:
// "<Black&
// White>"
format(stringToFormat, formattingArguments)
Signature
public static String format(String stringToFormat, List<Object> formattingArguments)
Return Value
Type: String
Versioned Behavior Changes
From version 51.0 and later, the format() method supports single quotes in the stringToFormat parameter and returns a formatted string using the formattingArguments parameter. In version 50.0 and earlier, single quotes weren’t supported.
Example
String template = '{0} was last updated {1}';
List<Object> parameters = new List<Object> {'Universal Containers', DateTime.newInstance(2018, 11, 15) };
String formatted = String.format(template, parameters);
System.debug ('Newly formatted string is:' + formatted);
fromCharArray(charArray)
Signature
public static String fromCharArray(List<Integer> charArray)
Return Value
Type: String
Example
List<Integer> charArr= new Integer[]{74};
String convertedChar = String.fromCharArray(charArr);
System.assertEquals('J', convertedChar);
getChars()
Signature
public List<Integer> getChars()
Return Value
A list of integers, each corresponding to a character value in the string.
Example
This sample converts a string to a character array and then gets the first array element, which corresponds to the value of 'J'.
String str = 'Jane goes fishing.';
Integer[] chars = str.getChars();
// Get the value of 'J'
System.assertEquals(74, chars[0]);
Usage
If a "/" (slash) character is present in the string, String.getChars() unescapes it in the returned character array. This example uses the String.escapeJava() method to generate the desired value of "\\" in the returned string.
String doubleSlash = '\\' + '\\'; //doubleSlash is set to "\\"
System.debug(String.fromCharArray(doubleSlash.getChars())); //Returns "\"
System.debug(String.fromCharArray(doubleSlash.escapeJava().getChars())); //Returns "\\”
getCommonPrefix(strings)
Signature
public static String getCommonPrefix(List<String> strings)
Return Value
Type: String
Example
List<String> ls = new List<String>{'SFDCApex', 'SFDCVisualforce'};
String prefix = String.getCommonPrefix(ls);
System.assertEquals('SFDC', prefix);
getLevenshteinDistance(stringToCompare)
Signature
public Integer getLevenshteinDistance(String stringToCompare)
Parameters
- stringToCompare
- Type: String
Return Value
Type: Integer
Usage
The Levenshtein distance is the number of changes needed to change one String into another. Each change is a single character modification (deletion, insertion or substitution).
Example
String s = 'Hello Joe';
Integer i = s.getLevenshteinDistance('Hello Max');
System.assertEquals(3, i);
getLevenshteinDistance(stringToCompare, threshold)
Signature
public Integer getLevenshteinDistance(String stringToCompare, Integer threshold)
Return Value
Type: Integer
Usage
The Levenshtein distance is the number of changes needed to change one String into another. Each change is a single character modification (deletion, insertion or substitution).
Example:
In this example, the Levenshtein distance is 3, but the threshold argument is 2, which is less than the distance, so this method returns -1.
Example
String s = 'Hello Jane';
Integer i = s.getLevenshteinDistance('Hello Max', 2);
System.assertEquals(-1, i);
hashCode()
Signature
public Integer hashCode()
Return Value
Type: Integer
Usage
This value is based on the hash code computed by the Java String.hashCode counterpart method.
You can use this method to simplify the computation of a hash code for a custom type that contains String member variables. You can compute your type’s hash code value based on the hash code of each String variable. For example:
For more details about the use of hash code methods with custom types, see Using Custom Types in Map Keys and Sets.
Example
public class MyCustomClass {
String x,y;
// Provide a custom hash code
public Integer hashCode() {
return
(31*x.hashCode())^(y.hashCode());
}
}
indexOf(substring)
Signature
public Integer indexOf(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Example
String myString1 = 'abcde';
String myString2 = 'cd';
Integer result = myString1.indexOf(mystring2);
System.assertEquals(2, result);
indexOf(substring, index)
Signature
public Integer indexOf(String substring, Integer index)
Return Value
Type: Integer
Example
String myString1 = 'abcdabcd';
String myString2 = 'ab';
Integer result = myString1.indexOf(mystring2, 1);
System.assertEquals(4, result);
indexOfAny(substring)
Signature
public Integer indexOfAny(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Example
String s1 = 'abcd';
String s2 = 'xc';
Integer result = s1.indexOfAny(s2);
System.assertEquals(2, result);
indexOfAnyBut(substring)
Signature
public Integer indexOfAnyBut(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Example
String s1 = 'abcd';
String s2 = 'xc';
Integer result = s1.indexOfAnyBut(s2);
System.assertEquals(0, result);
indexOfChar(character)
Signature
public Integer indexOfChar(Integer character)
Parameters
- character
- Type: Integer
- The integer value of the character in the string.
Return Value
Type: Integer
The index of the first occurrence of the specified character, -1 if the character is not found.
Usage
The index that this method returns is in Unicode code units.
Example
String str = '\\u03A9 is Ω (Omega)';
// Returns 0, which is the first character.
System.debug('indexOfChar(937)=' + str.indexOfChar(937));
// Output:
// indexOfChar(937)=0
indexOfChar(character, startIndex)
Signature
public Integer indexOfChar(Integer character, Integer startIndex)
Parameters
Return Value
Type: Integer
The index, starting from the specified start index, of the first occurrence of the specified character, -1 if the character is not found.
Usage
The index that this method returns is in Unicode code units.
Example
This example shows different ways of searching for the index of the Omega character. The first call to indexOfChar doesn’t specify a start index and therefore the returned index is 0, which is the first occurrence of Omega in the entire string. The subsequent calls specify a start index to find the occurrence of Omega in substrings that start at the specified index.
String str = 'Ω and \\u03A9 and Ω';
System.debug('indexOfChar(937)=' + str.indexOfChar(937));
System.debug('indexOfChar(937,1)=' + str.indexOfChar(937,1));
System.debug('indexOfChar(937,10)=' + str.indexOfChar(937,10));
// Output:
// indexOfChar(937)=0
// indexOfChar(937,1)=6, (corresponds to the escaped form \\u03A9)
// indexOfChar(937,10)=12
indexOfDifference(stringToCompare)
Signature
public Integer indexOfDifference(String stringToCompare)
Parameters
- stringToCompare
- Type: String
Return Value
Type: Integer
Example
String s1 = 'abcd';
String s2 = 'abxc';
Integer result = s1.indexOfDifference(s2);
System.assertEquals(2, result);
indexOfIgnoreCase(substring)
Signature
public Integer indexOfIgnoreCase(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Example
String s1 = 'abcd';
String s2 = 'BC';
Integer result = s1.indexOfIgnoreCase(s2, 0);
System.assertEquals(1, result);
indexOfIgnoreCase(substring, startPosition)
Signature
public Integer indexOfIgnoreCase(String substring, Integer startPosition)
Return Value
Type: Integer
isAllLowerCase()
Signature
public Boolean isAllLowerCase()
Return Value
Type: Boolean
Example
String allLower = 'abcde';
System.assert(allLower.isAllLowerCase());
isAllUpperCase()
Signature
public Boolean isAllUpperCase()
Return Value
Type: Boolean
Example
String allUpper = 'ABCDE';
System.assert(allUpper.isAllUpperCase());
isAlpha()
Signature
public Boolean isAlpha()
Return Value
Type: Boolean
Example
// Letters only
String s1 = 'abc';
// Returns true
Boolean b1 =
s1.isAlpha();
System.assertEquals(
true, b1);
// Letters and numbers
String s2 = 'abc 21';
// Returns false
Boolean b2 =
s2.isAlpha();
System.assertEquals(
false, b2);
isAlphaSpace()
Signature
public Boolean isAlphaSpace()
Return Value
Type: Boolean
Example
String alphaSpace = 'aA Bb';
System.assert(alphaSpace.isAlphaSpace());
String notAlphaSpace = 'ab 12';
System.assert(!notAlphaSpace.isAlphaSpace());
notAlphaSpace = 'aA$Bb';
System.assert(!notAlphaSpace.isAlphaSpace());
isAlphanumeric()
Signature
public Boolean isAlphanumeric()
Return Value
Type: Boolean
Example
// Letters only
String s1 = 'abc';
// Returns true
Boolean b1 =
s1.isAlphanumeric();
System.assertEquals(
true, b1);
// Letters and numbers
String s2 = 'abc021';
// Returns true
Boolean b2 =
s2.isAlphanumeric();
System.assertEquals(
true, b2);
isAlphanumericSpace()
Signature
public Boolean isAlphanumericSpace()
Return Value
Type: Boolean
Example
String alphanumSpace = 'AE 86';
System.assert(alphanumSpace.isAlphanumericSpace());
String notAlphanumSpace = 'aA$12';
System.assert(!notAlphanumSpace.isAlphaSpace());
isAsciiPrintable()
Signature
public Boolean isAsciiPrintable()
Return Value
Type: Boolean
Example
String ascii = 'abcd1234!@#$%^&*()`~-_+={[}]|:<,>.?';
System.assert(ascii.isAsciiPrintable());
String notAscii = '√';
System.assert(!notAscii.isAsciiPrintable());
isBlank(inputString)
Signature
public static Boolean isBlank(String inputString)
Parameters
- inputString
- Type: String
Return Value
Type: Boolean
Example
String blank = '';
String nullString = null;
String whitespace = ' ';
System.assert(String.isBlank(blank));
System.assert(String.isBlank(nullString));
System.assert(String.isBlank(whitespace));
String alpha = 'Hello';
System.assert(!String.isBlank(alpha));
isEmpty(inputString)
Signature
public static Boolean isEmpty(String inputString)
Parameters
- inputString
- Type: String
Return Value
Type: Boolean
Example
String empty = '';
String nullString = null;
System.assert(String.isEmpty(empty));
System.assert(String.isEmpty(nullString));
String whitespace = ' ';
String alpha = 'Hello';
System.assert(!String.isEmpty(whitespace));
System.assert(!String.isEmpty(alpha));
isNotBlank(inputString)
Signature
public static Boolean isNotBlank(String inputString)
Parameters
- inputString
- Type: String
Return Value
Type: Boolean
Example
String alpha = 'Hello world!';
System.assert(String.isNotBlank(alpha));
String blank = '';
String nullString = null;
String whitespace = ' ';
System.assert(!String.isNotBlank(blank));
System.assert(!String.isNotBlank(nullString));
System.assert(!String.isNotBlank(whitespace));
isNotEmpty(inputString)
Signature
public static Boolean isNotEmpty(String inputString)
Parameters
- inputString
- Type: String
Return Value
Type: Boolean
Example
String whitespace = ' ';
String alpha = 'Hello world!';
System.assert(String.isNotEmpty(whitespace));
System.assert(String.isNotEmpty(alpha));
String empty = '';
String nullString = null;
System.assert(!String.isNotEmpty(empty));
System.assert(!String.isNotEmpty(nullString));
isNumeric()
Signature
public Boolean isNumeric()
Return Value
Type: Boolean
Example
String numeric = '1234567890';
System.assert(numeric.isNumeric());
String alphanumeric = 'R32';
String decimalPoint = '1.2';
System.assert(!alphanumeric.isNumeric());
System.assert(!decimalpoint.isNumeric());
isNumericSpace()
Signature
public Boolean isNumericSpace()
Return Value
Type: Boolean
Usage
A decimal point (1.2) is not a Unicode digit.
Example
String numericSpace = '1 2 3';
System.assert(numericSpace.isNumericspace());
String notNumericspace = 'FD3S FC3S';
System.assert(!notNumericspace.isNumericspace());
isWhitespace()
Signature
public Boolean isWhitespace()
Return Value
Type: Boolean
Example
String whitespace = ' ';
String blank = '';
System.assert(whitespace.isWhitespace());
System.assert(blank.isWhitespace());
String alphanum = 'SIL80';
System.assert(!alphanum.isWhitespace());
join(iterableObj, separator)
Signature
public static String join(Object iterableObj, String separator)
Parameters
- iterableObj
- Type: Object
- separator
- Type: String
Return Value
Type: String
Usage
List<Integer> li = new
List<Integer>
{10, 20, 30};
String s = String.join(
li, '/');
System.assertEquals(
'10/20/30', s);
lastIndexOf(substring)
Signature
public Integer lastIndexOf(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Example
String s1 = 'abcdefgc';
Integer i1 = s1.lastIndexOf('c');
System.assertEquals(7, i1);
lastIndexOf(substring, endPosition)
Signature
public Integer lastIndexOf(String substring, Integer endPosition)
Return Value
Type: Integer
Usage
If the substring doesn’t occur or endPosition is negative, this method returns -1. If endPosition is larger than the last index in the current String, the entire String is searched.
Example
String s1 = 'abcdaacd';
Integer i1 = s1.lastIndexOf('c', 7);
System.assertEquals(6, i1);
Integer i2 = s1.lastIndexOf('c', 3);
System.assertEquals(2, i2);
lastIndexOfChar(character)
Signature
public Integer lastIndexOfChar(Integer character)
Parameters
- character
- Type: Integer
- The integer value of the character in the string.
Return Value
Type: Integer
The index of the last occurrence of the specified character, -1 if the character is not found.
Usage
The index that this method returns is in Unicode code units.
Example
String str = '\u03A9 is Ω (Omega)';
// Get the last occurrence of Omega.
System.assertEquals(5, str.lastIndexOfChar(937));
lastIndexOfChar(character, endIndex)
Signature
public Integer lastIndexOfChar(Integer character, Integer endIndex)
Parameters
Return Value
Type: Integer
The index, starting from the specified start index, of the last occurrence of the specified character. -1 if the character is not found.
Usage
The index that this method returns is in Unicode code units.
Example
This example shows different ways of searching for the index of the last occurrence of the Omega character. The first call to lastIndexOfChar doesn’t specify an end index and therefore the returned index is 12, which is the last occurrence of Omega in the entire string. The subsequent calls specify an end index to find the last occurrence of Omega in substrings.
String str = 'Ω and \u03A9 and Ω';
System.assertEquals(12, str.lastIndexOfChar(937));
System.assertEquals(6, str.lastIndexOfChar(937,11));
System.assertEquals(0, str.lastIndexOfChar(937,5));
lastIndexOfIgnoreCase(substring)
Signature
public Integer lastIndexOfIgnoreCase(String substring)
Parameters
- substring
- Type: String
Return Value
Type: Integer
Usage
If the substring doesn’t occur, this method returns -1.
Example
String s1 = 'abcdaacd';
Integer i1 = s1.lastIndexOfIgnoreCase('DAAC');
System.assertEquals(3, i1);
lastIndexOfIgnoreCase(substring, endPosition)
Signature
public Integer lastIndexOfIgnoreCase(String substring, Integer endPosition)
Return Value
Type: Integer
Usage
If the substring doesn’t occur or endPosition is negative, this method returns -1. If endPosition is larger than the last index in the current String, the entire String is searched.
Example
String s1 = 'abcdaacd';
Integer i1 = s1.lastIndexOfIgnoreCase('C', 7);
System.assertEquals(6, i1);
left(length)
Signature
public String left(Integer length)
Parameters
- length
- Type: Integer
Return Value
Type: String
Usage
If length is greater than the String size, the entire String is returned.
Example
String s1 = 'abcdaacd';
String s2 = s1.left(3);
System.assertEquals('abc', s2);
leftPad(length)
Signature
public String leftPad(Integer length)
Parameters
- length
- Type: Integer
Usage
If length is less than or equal to the current String size, the entire String is returned without space padding.
Return Value
Type: String
Example
String s1 = 'abc';
String s2 = s1.leftPad(5);
System.assertEquals(' abc', s2);
leftPad(length, padStr)
Signature
public String leftPad(Integer length, String padStr)
Parameters
Usage
If length is less than or equal to the current String size, the entire String is returned without space padding.
Return Value
Type: String
Example
String s1 = 'abc';
String s2 = 'xy';
String s3 = s1.leftPad(7,s2);
System.assertEquals('xyxyabc', s3);
length()
Signature
public Integer length()
Return Value
Type: Integer
Example
String myString = 'abcd';
Integer result = myString.length();
System.assertEquals(result, 4);
mid(startIndex, length)
Signature
public String mid(Integer startIndex, Integer length)
Parameters
Return Value
Type: String
Usage
This method is similar to the substring(startIndex) and substring(startIndex, endIndex) methods, except that the second argument is the number of characters to return.
Example
String s = 'abcde';
String s2 = s.mid(2, 3);
System.assertEquals(
'cde', s2);
normalizeSpace()
Signature
public String normalizeSpace()
Return Value
Type: String
Usage
This method normalizes the following white space characters: space, tab (\t), new line (\n), carriage return (\r), and form feed (\f).
Example
String s1 =
'Salesforce \t force.com';
String s2 =
s1.normalizeSpace();
System.assertEquals(
'Salesforce force.com', s2);
offsetByCodePoints(index, codePointOffset)
Signature
public Integer offsetByCodePoints(Integer index, Integer codePointOffset)
Parameters
Return Value
Type: Integer
The index that corresponds to the start index that is added to the offset.
Usage
Unpaired surrogates within the text range that is specified by index and codePointOffset count as one code point each.
Example
This example calls offsetByCodePoints on a string with a start index of 0 (to start from the first character) and an offset of three code points. The string contains one sequence of supplementary characters in escaped form (a pair of characters). After an offset of three code points when counting from the beginning of the string, the returned code point index is four.
String str = 'A \uD835\uDD0A BC';
System.assertEquals(4, str.offsetByCodePoints(0,3));
remove(substring)
Signature
public String remove(String substring)
Parameters
- substring
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce and force.com';
String s2 =
s1.remove('force');
System.assertEquals(
'Sales and .com', s2);
removeEnd(substring)
Signature
public String removeEnd(String substring)
Parameters
- substring
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce and force.com';
String s2 =
s1.removeEnd('.com');
System.assertEquals(
'Salesforce and force', s2);
removeEndIgnoreCase(substring)
Signature
public String removeEndIgnoreCase(String substring)
Parameters
- substring
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce and force.com';
String s2 = s1.removeEndIgnoreCase('.COM');
System.assertEquals('Salesforce and force', s2);
removeStart(substring)
Signature
public String removeStart(String substring)
Parameters
- substring
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce and force.com';
String s2 =
s1.removeStart('Sales');
System.assertEquals(
'force and force.com', s2);
removeStartIgnoreCase(substring)
Signature
public String removeStartIgnoreCase(String substring)
Parameters
- substring
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce and force.com';
String s2 =
s1.removeStartIgnoreCase('SALES');
System.assertEquals(
'force and force.com', s2);
repeat(separator, numberOfTimes)
Signature
public String repeat(String separator, Integer numberOfTimes)
Return Value
Type: String
Example
String s1 = 'SFDC';
String s2 =
s1.repeat('-', 2);
System.assertEquals(
'SFDC-SFDC', s2);
replace(target, replacement)
Signature
public String replace(String target, String replacement)
Return Value
Type: String
Example
String s1 = 'abcdbca';
String target = 'bc';
String replacement = 'xy';
String s2 = s1.replace(target, replacement);
System.assertEquals('axydxya', s2);
replaceAll(regExp, replacement)
Signature
public String replaceAll(String regExp, String replacement)
Return Value
Type: String
Usage
See the Java Pattern class for information on regular expressions.
Example
String s1 = 'a b c 5 xyz';
String regExp = '[a-zA-Z]';
String replacement = '1';
String s2 = s1.replaceAll(regExp, replacement);
System.assertEquals('1 1 1 5 111', s2);
replaceFirst(regExp, replacement)
Signature
public String replaceFirst(String regExp, String replacement)
Return Value
Type: String
Usage
See the Java Pattern class for information on regular expressions.
Example
String s1 = 'a b c 11 xyz';
String regExp = '[a-zA-Z]{2}';
String replacement = '2';
String s2 = s1.replaceFirst(regExp, replacement);
System.assertEquals('a b c 11 2z', s2);
reverse()
Signature
public String reverse()
Return Value
Type: String
right(length)
Signature
public String right(Integer length)
Parameters
- length
- Type: Integer
- If length is greater than the String size, the entire String is returned.
Return Value
Type: String
Example
String s1 = 'Hello Max';
String s2 =
s1.right(3);
System.assertEquals(
'Max', s2);
rightPad(length)
Signature
public String rightPad(Integer length)
Parameters
- length
- Type: Integer
- If length is less than or equal to the current String size, the entire String is returned without space padding.
Return Value
Type: String
Example
String s1 = 'abc';
String s2 =
s1.rightPad(5);
System.assertEquals(
'abc ', s2);
rightPad(length, padStr)
Signature
public String rightPad(Integer length, String padStr)
Parameters
Usage
If length is less than or equal to the current String size, the entire String is returned without space padding.
Return Value
Type: String
Example
String s1 = 'abc';
String s2 = 'xy';
String s3 = s1.rightPad(7, s2);
System.assertEquals('abcxyxy', s3);
split(regExp)
Signature
public String[] split(String regExp)
Parameters
- regExp
- Type: String
Return Value
Type: String[]
Usage
See the Java Pattern class for information on regular expressions.
The substrings are placed in the list in the order in which they occur in the String. If regExp does not match any part of the String, the resulting list has just one element containing the original String.
Example
In the following example, a string is split using a backslash as a delimiter.
public String splitPath(String filename) {
if (filename == null)
return null;
List<String> parts = filename.split('\\\\');
filename = parts[parts.size()-1];
return filename;
}
// For example, if the file path is e:\\processed\\PPDSF100111.csv
// This method splits the path and returns the last part.
// Returned filename is PPDSF100111.csv
split(regExp, limit)
Signature
public String[] split(String regExp, Integer limit)
Return Value
Type: String[]
Usage
- If limit is greater than zero:
- The pattern is applied a maximum of (limit – 1) times.
- The list’s length is no greater than limit.
- The list’s last entry contains all input beyond the last matched delimiter.
- If limit is non-positive, the pattern is applied as many times as possible, and the list can have any length.
- If limit is zero, the pattern is applied as many times as possible, the list can have any length, and trailing empty strings are discarded.
Example
- s.split(':', 2) results in {'boo', 'and:moo'}
- s.split(':', 5) results in {'boo', 'and', 'moo'}
- s.split(':', -2) results in {'boo', 'and', 'moo'}
- s.split('o', 5) results in {'b', '', ':and:m', '', ''}
- s.split('o', -2) results in {'b', '', ':and:m', '', ''}
- s.split('o', 0) results in {'b', '', ':and:m'}
splitByCharacterType()
Signature
public List<String> splitByCharacterType()
Usage
For more information about the character types used, see java.lang.Character.getType(char).
Example
String s1 = 'Lightning.platform';
List<String> ls =
s1.splitByCharacterType();
System.debug(ls);
// Writes this output:
// (L, ightning, ., platform)
splitByCharacterTypeCamelCase()
Signature
public List<String> splitByCharacterTypeCamelCase()
Usage
For more information about the character types used, see java.lang.Character.getType(char).
Example
String s1 = 'Lightning.platform';
List<String> ls =
s1.splitByCharacterTypeCamelCase();
System.debug(ls);
// Writes this output:
// (Lightning, ., platform)
startsWithIgnoreCase(prefix)
Signature
public Boolean startsWithIgnoreCase(String prefix)
Parameters
- prefix
- Type: String
Return Value
Type: Boolean
Example
String s1 = 'AE86 vs EK9';
System.assert(s1.startsWithIgnoreCase('ae86'));
stripHtmlTags()
Signature
public String stripHtmlTags()
Return Value
Type: String
Usage
Example
String s1 = '<b>hello world</b>';
String s2 = s1.stripHtmlTags();
System.assertEquals(
'hello world', s2);
substring(startIndex)
Signature
public String substring(Integer startIndex)
Parameters
- startIndex
- Type: Integer
Return Value
Type: String
Example
String s1 = 'hamburger';
System.assertEquals('burger', s1.substring(3));
substring(startIndex, endIndex)
Signature
public String substring(Integer startIndex, Integer endIndex)
Return Value
Type: String
Example
'hamburger'.substring(4, 8);
// Returns "urge"
'smiles'.substring(1, 5);
// Returns "mile"
substringAfter(separator)
Signature
public String substringAfter(String separator)
Parameters
- separator
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce.Lightning.platform';
String s2 =
s1.substringAfter('.');
System.assertEquals(
'Lightning.platform', s2);
substringAfterLast(separator)
Signature
public String substringAfterLast(String separator)
Parameters
- separator
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce.Lightning.platform';
String s2 =
s1.substringAfterLast('.');
System.assertEquals(
'platform', s2);
substringBefore(separator)
Signature
public String substringBefore(String separator)
Parameters
- separator
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce.Lightning.platform';
String s2 =
s1.substringBefore('.');
System.assertEquals(
'Salesforce', s2);
substringBeforeLast(separator)
Signature
public String substringBeforeLast(String separator)
Parameters
- separator
- Type: String
Return Value
Type: String
Example
String s1 = 'Salesforce.Lightning.platform';
String s2 =
s1.substringBeforeLast('.');
System.assertEquals(
'Salesforce.Lightning', s2);
substringBetween(tag)
Signature
public String substringBetween(String tag)
Parameters
- tag
- Type: String
Return Value
Type: String
Example
String s1 = 'tagYellowtag';
String s2 = s1.substringBetween('tag');
System.assertEquals('Yellow', s2);
substringBetween(open, close)
Signature
public String substringBetween(String open, String close)
Return Value
Type: String
Example
String s1 = 'xYellowy';
String s2 =
s1.substringBetween('x','y');
System.assertEquals(
'Yellow', s2);
swapCase()
Signature
public String swapCase()
Return Value
Type: String
Usage
Upper case and title case converts to lower case, and lower case converts to upper case.
Example
String s1 = 'Force.com';
String s2 = s1.swapCase();
System.assertEquals('fORCE.COM', s2);
toLowerCase()
Signature
public String toLowerCase()
Return Value
Type: String
Example
String s1 = 'ThIs iS hArD tO rEaD';
System.assertEquals('this is hard to read',
s1.toLowerCase());
toLowerCase(locale)
Signature
public String toLowerCase(String locale)
Parameters
- locale
- Type: String
Return Value
Type: String
Example
// Example in Turkish
// An uppercase dotted "i", \u0304, which is İ
// Note this contains both a İ as well as a I
String s1 = 'KIYMETLİ';
String s1Lower = s1.toLowerCase('tr');
// Dotless lowercase "i", \u0131, which is ı
// Note this has both a i and ı
String expected = 'kıymetli';
System.assertEquals(expected, s1Lower);
// Note if this was done in toLowerCase(‘en’), it would output ‘kiymetli’
toUpperCase()
Signature
public String toUpperCase()
Return Value
Type: String
Example
String myString1 = 'abcd';
String myString2 = 'ABCD';
myString1 =
myString1.toUpperCase();
Boolean result =
myString1.equals(myString2);
System.assertEquals(result, true);
toUpperCase(locale)
Signature
public String toUpperCase(String locale)
Parameters
- locale
- Type: String
Return Value
Type: String
Example
// Example in Turkish
// Dotless lowercase "i", \u0131, which is ı
// Note this has both a i and ı
String s1 = 'imkansız';
String s1Upper = s1.toUpperCase('tr');
// An uppercase dotted "i", \u0304, which is İ
// Note this contains both a İ as well as a I
String expected = 'İMKANSIZ';
System.assertEquals(expected, s1Upper);
trim()
Signature
public String trim()
Return Value
Type: String
Usage
Leading and trailing ASCII control characters such as tabs and newline characters are also removed. White space and control characters that aren’t at the beginning or end of the sentence aren’t removed.
Example
String s1 = ' Hello! ';
String trimmed = s1.trim();
system.assertEquals('Hello!', trimmed);
uncapitalize()
Signature
public String uncapitalize()
Return Value
Type: String
Example
String s1 =
'Hello max';
String s2 =
s1.uncapitalize();
System.assertEquals(
'hello max',
s2);
unescapeCsv()
Signature
public String unescapeCsv()
Return Value
Type: String
Usage
If the String is enclosed in double quotes and contains a comma, newline or double quote, quotes are removed. Also, any double quote escaped characters (a pair of double quotes) are unescaped to just one double quote.
If the String is not enclosed in double quotes, or is and does not contain a comma, newline or double quote, it is returned unchanged.
Example
String s1 =
'"Max1, ""Max2"""';
String s2 =
s1.unescapeCsv();
System.assertEquals(
'Max1, "Max2"',
s2);
unescapeEcmaScript()
Signature
public String unescapeEcmaScript()
Return Value
Type: String
Example
String s1 =
'\"3.8\",\"3.9\"';
String s2 =
s1.unescapeEcmaScript();
System.assertEquals(
'"3.8","3.9"',
s2);
unescapeHtml3()
Signature
public String unescapeHtml3()
Return Value
Type: String
Example
String s1 =
'"<Black&White>"';
String s2 =
s1.unescapeHtml3();
System.assertEquals(
'"<Black&White>"',
s2);
unescapeHtml4()
Signature
public String unescapeHtml4()
Return Value
Type: String
Usage
If an entity isn’t recognized, it is kept as is in the returned string.
Example
String s1 =
'"<Black&White>"';
String s2 =
s1.unescapeHtml4();
System.assertEquals(
'"<Black&White>"',
s2);
unescapeJava()
Signature
public String unescapeJava()
Example
String s = 'Company: \\"Salesforce.com\\"';
String unescapedStr = s.unescapeJava();
System.assertEquals('Company: "Salesforce.com"', unescapedStr);
unescapeUnicode()
Signature
public String unescapeUnicode()
Example
String s = 'De onde voc\u00EA \u00E9?';
String unescapedStr = s.unescapeUnicode();
System.assertEquals('De onde você é?', unescapedStr);
unescapeXml()
Signature
public String unescapeXml()
Return Value
Type: String
Usage
Supports only the five basic XML entities (gt, lt, quot, amp, apos). Does not support DTDs or external entities.
Example
String s1 =
'"<Black&White>"';
String s2 =
s1.unescapeXml();
System.assertEquals(
'"<Black&White>"',
s2);
valueOf(datetimeToConvert)
Signature
public static String valueOf(Datetime datetimeToConvert)
Parameters
- datetimeToConvert
- Type: Datetime
Return Value
Type: String
Example
DateTime dt = datetime.newInstance(1996, 6, 23);
String sDateTime = String.valueOf(dt);
System.assertEquals('1996-06-23 00:00:00', sDateTime);
valueOf(decimalToConvert)
Signature
public static String valueOf(Decimal decimalToConvert)
Parameters
- decimalToConvert
- Type: Decimal
Return Value
Type: String
Example
Decimal dec = 3.14159265;
String sDecimal = String.valueOf(dec);
System.assertEquals('3.14159265', sDecimal);
valueOf(doubleToConvert)
Signature
public static String valueOf(Double doubleToConvert)
Parameters
- doubleToConvert
- Type: Double
Return Value
Type: String
Example
Double myDouble = 12.34;
String myString =
String.valueOf(myDouble);
System.assertEquals(
'12.34', myString);
valueOf(integerToConvert)
Signature
public static String valueOf(Integer integerToConvert)
Parameters
- integerToConvert
- Type: Integer
Return Value
Type: String
Example
Integer myInteger = 22;
String sInteger = String.valueOf(myInteger);
System.assertEquals('22', sInteger);
valueOf(toConvert)
Signature
public static String valueOf(Object toConvert)
Parameters
- toConvert
- Type: Object
Return Value
Type: String
Usage
If the argument is not a String, the valueOf method converts it into a String by calling the toString method on the argument, if available, or any overridden toString method if the argument is a user-defined type. Otherwise, if no toString method is available, it returns a String representation of the argument.
Example
List<Integer> ls =
new List<Integer>();
ls.add(10);
ls.add(20);
String strList =
String.valueOf(ls);
System.assertEquals(
'(10, 20)', strList);
valueOfGmt(datetimeToConvert)
Signature
public static String valueOfGmt(Datetime datetimeToConvert)
Parameters
- datetimeToConvert
- Type: Datetime
Return Value
Type: String
Example
// For a PST timezone:
DateTime dt = datetime.newInstance(2001, 9, 14);
String sDateTime = String.valueOfGmt(dt);
System.assertEquals('2001-09-14 07:00:00', sDateTime);