String Methods

The following are the system static methods for String.

Name Arguments Return Type Description
escapeSingleQuotes String s String Returns a String with the escape character (\) added before any single quotation marks in the String s. This method is useful when creating a dynamic SOQL statement, to help prevent SOQL injection. For more information on dynamic SOQL, see Dynamic SOQL. See also Splitting String Example.
format String s

List<String> arguments

String Treat the current string as a pattern that should be used for substitution in the same manner as apex:outputText.
fromCharArray List<Integer> charArray String Returns a String from the values of the list of integers.
valueOf Date d String Returns a String that represents the specified Date in the standard “yyyy-MM-dd” format. For example:
Date myDate = Date.Today();
String sDate = String.valueOf(myDate);
valueOf Datetime dt String Returns a String that represents the specified Datetime in the standard “yyyy-MM-dd HH:mm:ss” format for the local time zone
valueOf Decimal d String Returns a String that represents the specified Decimal.
valueOf Double d String Returns a String that represents the specified Double.
valueOf Integer I String Returns a String that represents the specified Integer.
valueOf Long l String Returns a String that represents the specified Long.
valueOf anyType x* String Casts x, a history tracking table field of type anyType, to a String. For example:
Double myDouble = 12.34;
String myString = 
   String.valueOf(myDouble);
System.assertEquals('12.34', myString);

For more information on the anyType data type, see Field Types in the Object Reference for Database.com.

valueOfGmt Datetime dt String Returns a String that represents the specified Datetime in the standard “yyyy-MM-dd HH:mm:ss” format for the GMT time zone

The following are the instance methods for String.

Name Arguments Return Type Description
compareTo String compString Integer Compares two strings lexicographically, based on the Unicode value of each character in the Strings. The result is:
  • A negative Integer if the String that called the method lexicographically precedes compString
  • A positive Integer if the String that called the method lexicographically follows compString
  • 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. For example:
String myString1 = 'abcde';
String myString2 = 'abcd';
Integer result = 
   myString1.compareTo(myString2);
System.assertEquals(result, 1);

Note that this method returns 0 whenever the equals method returns true.

contains String compString Boolean Returns true if and only if the String that called the method contains the specified sequence of characters in the compString. For example:
String myString1 = 'abcde';
String myString2 = 'abcd';
Boolean result = 
   myString1.contains(myString2);
System.assertEquals(result, true);
endsWith String suffix Boolean Returns true if the String that called the method ends with the specified suffix
equals String compString Boolean Returns true if the compString is not null and represents the same binary sequence of characters as the String that called the method. This method is true whenever the compareTo method returns 0. For example:
String myString1 = 'abcde';
String myString2 = 'abcd';
Boolean result = 
   myString1.equals(myString2);
System.assertEquals(result, false);

Note that the == operator also performs String comparison, but is case-insensitive to match Apex semantics. (== is case-sensitive for ID comparison for the same reason.)

equalsIgnoreCase String compString Boolean Returns true if the compString is not null and represents the same sequence of characters as the String that called the method, ignoring case. For example:
String myString1 = 'abcd';
String myString2 = 'ABCD';
Boolean result = 
myString1.equalsIgnoreCase(myString2);
System.assertEquals(result, true);
indexOf String subString Integer Returns the index of the first occurrence of the specified substring. If the substring does not occur, this method returns -1.
indexOf String substring

Integer i

Integer Returns the index of the first occurrence of the specified substring from the point of index i. If the substring does not occur, this method returns -1. For example:
String myString1 = 'abcd';
String myString2 = 'bc';
Integer result = 
   myString1.indexOf(myString2, 0);
System.assertEquals(result, 1);
lastIndexOf String substring Integer Returns the index of the last occurrence of the specified substring. If the substring does not occur, this method returns -1.
length Integer Returns the number of 16-bit Unicode characters contained in the String. For example:
String myString = 'abcd';
Integer result = myString.length();
System.assertEquals(result, 4);
replace String target

String replacement

String Replaces each substring of a string that matches the literal target sequence target with the specified literal replacement sequence replacement
replaceAll String regExp

String replacement

String Replaces each substring of a string that matches the regular expression regExp with the replacement sequence replacement. See http://java.sun.com/j2se/1.5.0/docs/​api/java/util/regex/Pattern.html for information on regular expressions.
replaceFirst String regExp

String replacement

String Replaces the first substring of a string that matches the regular expression regExp with the replacement sequence replacement. See http://java.sun.com/j2se/1.5.0/docs/​api/java/util/regex/Pattern.html for information on regular expressions.
split String regExp

Integer limit

String[] Returns a list that contains each substring of the String that is terminated by the regular expression regExp, or the end of the String. See http://java.sun.com/j2se/1.5.0/docs/​api/java/util/regex/Pattern.html 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.

The optional limit parameter controls the number of times the pattern is applied and therefore affects the length of the list:
  • If limit is greater than zero, the pattern is applied at most limit - 1 times, the list's length is no greater than limit, and the list's last entry contains all input beyond the last matched delimiter.
  • If limit is non-positive then the pattern is applied as many times as possible and the list can have any length.
  • If limit is zero then the pattern is applied as many times as possible, the list can have any length, and trailing empty strings are discarded.
For example, for String s = 'boo:and:foo':
  • s.split(':', 2) results in {'boo', 'and:foo'}
  • s.split(':', 5) results in {'boo', 'and', 'foo'}
  • s.split(':', -2) results in {'boo', 'and', 'foo'}
  • s.split('o', 5) results in {'b', '', ':and:f', '', ''}
  • s.split('o', -2) results in {'b', '', ':and:f', '', ''}
  • s.split('o', 0) results in {'b', '', ':and:f'}

See also Splitting String Example.

startsWith String prefix Boolean Returns true if the String that called the method begins with the specified prefix
substring Integer startIndex String Returns a new String that begins with the character at the specified startIndex and extends to the end of the String
substring Integer startIndex,

Integer endIndex

String Returns a new String that begins with the character at the specified startIndex and extends to the character at endIndex - 1. For example:
'hamburger'.substring(4, 8); 
// Returns "urge" 
    

'smiles'.substring(1, 5);
// Returns "mile" 
    
toLowerCase String Converts all of the characters in the String to lowercase using the rules of the default locale
toLowerCase String locale String Converts all of the characters in the String to lowercase using the rules of the specified locale
toUpperCase String Converts all of the characters in the String to uppercase using the rules of the default locale. For example:
String myString1 = 'abcd';
String myString2 = 'ABCD';
myString1 = 
   myString1.toUpperCase();
Boolean result = 
   myString1.equals(myString2);
System.assertEquals(result, true);
toUpperCase String locale String Converts all of the characters in the String to the uppercase using the rules of the specified locale
trim String Returns a copy of the string that no longer contains any leading or trailing white space characters.

Leading and trailing ASCII control characters such as tabs and newline characters are also removed. Whitespace and control characters that aren’t at the beginning or end of the sentence aren’t removed.

For more information on Strings, see Primitive Data Types.

Splitting String Example

In the following example, a string is split, using a backslash as a delimiter:
public String removePath(String filename) {
        if (filename == null)
            return null;
        List<String> parts = filename.split('\\\\');
        filename = parts[parts.size()-1];
        return filename;
    }

    static testMethod void testRemovePath() {
        System.assertEquals('PPDSF100111.csv', 
                EmailUtilities.getInstance().
                removePath('e:\\processed\\PPDSF100111.csv'));
    } 
© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.