Last month, in the Winter ’13 Release Preview webinar, Dave and Sam mentioned that the Apex String class gains a number of new methods in this release; 68 to be exact. Every Apex developer should study the new methods in detail – using them will improve performance, make your code more readable and consume fewer script statements. Some of the new methods in particular carry such savings that you might even want to go back and refactor existing code to use them. In this blog entry, I’ll highlight one method from each of the groups listed in the Winter ’13 release notes. Download the release notes, open the Apex String documentation page and read on…

Manipulating Strings

First, let’s look at join, a static method that joins the elements of any iterable object, such as a List, into a String separated by a given separator. Here’s the example from the Apex docs

List<Integer> li = new List<Integer>{10, 20, 30};
String s = String.join(li, '/');
System.assertEquals('10/20/30', s);

As you can see, in a single method call we can join an arbitrary number of elements into a single string – for even the simple example shown, using a for loop consumes 9 script statements instead of the 3 above; as the list size increases the savings multiply, exponentially if we are processing records in a loop.

Changing/checking case

In this set of methods, you might not need swapCase often, but you’ll be glad of it when you do. As its name implies, it simply swaps the case of all characters in a string:

String s1 = '';
String s2 = s1.swapCase();
System.assertEquals('fORCE.COM', s2);

Without swapCase, there is no way to achieve this result without scanning through the string character by character, consuming a number of script statements proportional to the string length. With swapCase, of course, you can swap the case of a string of any length in a single script statement.

Searching/extracting substrings

Here, countMatches achieves a simple goal, counting the number of times the specified substring occurs in the current String, but think of the code you would have to write in its absence – something like:

String needle = 'ABC';

String str = haystack;
Integer needleLen = needle.length();
Integer count = 0;
Integer index = str.indexOf(needle);
while (index >= 0) {
    str = str.substring(index+needleLen);
    index = str.indexOf(needle);
System.assertEquals(count, 5);

Here, although we’re only burning through three script statements per match, this would quickly become significant if you were, for example, counting occurrences of a common word in a sizable piece of text.

Escaping/unescaping Strings

Nothing really stands out here – there are methods to escape and unescape CSV, ‘EcmaScript‘ (aka JavaScript!), HTML3, HTML4 and XML, each based on its counterpart in the Apache Commons Lang StringEscapeUtils library. It almost goes without saying that you would consume several script statements per character of input implementing any of these ‘by hand’.

String s1 = '"<Black&White>"';
String s2 = s1.escapeXml();
System.assertEquals('&quot;&lt;Black&amp;White&gt;&quot;', s2);

Determining the type of characters in a String

A family of closely related methods, here’s the usage for isAlphanumeric:

String s1 = 'abc123';
Boolean b1 = s1.isAlphanumeric();
System.assertEquals(true, b1);
String s2 = 'abc!@#';
Boolean b2 = s2.isAlphanumeric();
System.assertEquals(false, b2);

Pre-Winter ’13, you would have to roll your own test for alphanumericity (is that even a word?) and scan through the string character-by-character. Not fun.

Other utility methods

My eye is immediately drawn to getLevenshteinDistanceWikipedia says, ‘the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is equal to the number of single-character edits required to change one word into the other’. One application of Levenshtein distance is to figure out if one word is likely a typo of another:

String input = 'forrce';
Integer force = input.getLevenshteinDistance('force');
Integer forest = input.getLevenshteinDistance('forest');
System.assert(force < forest);

So, there you have it, 68 shiny new toys for every Apex developer. Which is your favorite? Leave a comment and let us know!

Photo credit:

tagged , , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • Chirag Mehta

    wow .. 68 .. thts big no ..thank you this will really ease the code a lot and make it more readable .. lot to go yet …

  • Ankit Arora

    Ready to use.

  • sandeep R

    I always wanted the join method….

  • Ansuman Patnaik

    isAlphanumeric() should be included in Validation Rules …

  • Shivanath

    escapeXml/unescapeXml, isAlphanumeric, normalizeSpace are really helpful !

  • Osama Nasir

    String.Join() is what I will be using a lot!

  • Harshit Pandey

    using them :-)

  • Andrea Morales

    hi, the new methods are really great.
    This might be a silly question but .. In the join method, if I have a list of objects, can I specify which field should be used ?

  • Keith Clarke

    With the Winter ’13 support for user defined types via equals/hashCode, the lack of a hashCode amongst these new methods makes creating a user-defined types that has one or more string fields much more painful than it should be.

    Please expose a hashCode method on string.

    • Pat Patterson

      Hi Keith – I passed your request for String.hashCode on to the Apex PM. In the meantime, you could create a user-defined wrapper type around String and implement HashCode. Not perfect, but straightforward.