Use the String data type when you need to store text values, such as a name or an address. Strings are sets of characters enclosed in single quotes. For example, 'I am a string'. You can create a string and assign it to a variable simply by executing the following:
String myVariable = 'I am a string.';
The previous example creates an instance of the String class, represented by the variable myVariable, and assigns it a string value between single quotes.
You can also create strings from the values of other types, such as dates, by using the String static method valueOf(). Execute the following:
Date myDate = Date.today(); String myString = String.valueOf(myDate); System.debug(myString);
The output of this example should be today’s date. For example, 2012-03-15. You’ll likely see a different date.
The + operator acts as a concatenation operator when applied to strings. The following results in a single string being created:
System.debug( 'I am a string' + ' cheese');
The == and != operators act as a case insensitive comparisons. Execute the following to confirm that both the comparisons below return true:
String x = 'I am a string'; String y = 'I AM A STRING'; String z = 'Hello!'; System.debug (x == y); System.debug (x != z);
The String class has many instance methods that you can use to manipulate or interrogate a string. Execute the following:
String x = 'The !shorn! sheep !sprang!.'; System.debug (x.endsWith('.')); System.debug (x.length()); System.debug (x.substring(5,10)); System.debug (x.replaceAll ('!(.*?)!', '$1'));
This is the output.
Let’s take a look at what each method does.
- The endsWith method returns true because the string ends with the same string as that in the argument.
- The length method returns the length of the string.
- The substring method produces a new string starting from the character specified in the first index argument, counting from zero, through the second argument.
- The replaceAll method replaces each substring that matches a regular expression with the specified replacement. In this case, we match for text within exclamation points, and replace that text with what was matched (the $1).
No comments:
Post a Comment