Wednesday, 29 August 2012

String - Apex Language Fundamentals


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.

Output of String method results
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).
Tip
You can filter the log output in the Developer Console to view only lines that contain “USER_DEBUG”. See Tutorial 2: Lesson 2 for steps of how to do this. That way, you can view only the debug statements of the previous example without having to read the whole log output.

Filtering log output in the Developer Console for USER_DEBUG statements
In addition, you can set the log level of System to Info in the Developer Console to exclude logging of system methods. To access the log levels, click Log Levelsand then set System to Info.

Setting log levels in the Developer Console

No comments:

Post a Comment