Apex String Class & Methods with Techniques

Apex String Class

Do you shudder when facing string manipulation tasks in Apex? As a Salesforce developer, efficiently parsing, modifying, and validating strings is a non-negotiable skill. However, the extensive Apex String library can seem utterly overwhelming at times.

Take a deep breath – help is here! In this comprehensive guide, you’ll discover everything you need to master the art of string handling in Apex.

I’ll provide you with an easy-to-follow Apex string cheatsheet covering the most indispensable methods and techniques modern developers must have in their toolkits. You’ll learn best practices for essential tasks like splitting, formatting, comparing strings, sanitizing inputs, and flexible data conversions.

By the end, you’ll feel right at home with strings, no matter the complexity of your requirements. Become the string bender that effortlessly transforms JSON responses into readable formats, generates dynamic HTML emails, and writes clean, lean code that wows your teammates!

So, if you’re looking to level up your string skills, buckle up! You’re about to become a string manipulation master.

TL;DR

  1. Use essential string methods like split(), contains(), replace() etc. to transform, evaluate, excerpt strings.
  2. Master techniques for common string-handling tasks like concatenation, escape sequences, and multi-line strings.
  3. Validate and compare strings using equals(), length() and other comparison methods.
  4. Convert between data types like Boolean, Integer, and Date using valueOf() and parse() methods.
  5. Handle string-heavy tasks elegantly, like input validation dynamic text generation, using the concepts learnt.

Mastering Strings in Apex

What Are Strings in Apex?

In Salesforce’s Apex programming language, a “string” is a sequence of characters. Strings can include anything from words, sentences, and code snippets to random combinations of letters and symbols. It’s important to familiarize yourself with strings in Apex as they play a crucial role in many common programming tasks.

For example, let’s consider this simple string in Apex:


String myString = 'Hello, Apex World!';

In this case, the variable myString now holds the given string, which can be used and manipulated later in your code.

Why String Manipulation is Important

String manipulation is a fundamental skill you’ll need throughout your journey in Apex programming. Here’s why it’s important:

  • Data Transformation: Often, you’ll be required to extract, transform, or format data to meet specific requirements. Working with strings effectively can make these tasks easier and more efficient.
  • Validation: When gathering user input or processing data from external sources, you must validate and sanitize the information to ensure accuracy and maintain data integrity.
  • Code Readability: Properly formatted strings contribute to cleaner and more easily understandable code, promoting efficient collaboration.

As you progress in your Apex journey, you’ll discover the various powerful string methods that Salesforce provides to help streamline these tasks. Mastering these methods will equip you to tackle string manipulation with confidence and efficiency. Stay tuned for the next sections, where we’ll dive into essential Salesforce Apex String Methods and other valuable string manipulation techniques.

Salesforce Apex String Methods

Handling strings in Apex entails various methods to transform, excerpt, or evaluate your string data. Let’s dive into each one.

split()

The split() method slices a string around matches of the given delimiter. It returns a list of strings computed by splitting the original string.


String str = 'Hello, Apex World!';
List strList = str.split(',');

In this case, strList would become {'Hello', ' Apex World!'}.

indexOf()

indexOf() retrieves the position of the first occurrence of a specified value in a string. If the value is not found, it returns -1.


String str = 'Hello, Apex World!';
Integer pos = str.indexOf('Apex');

Here, pos equals 7 because ‘Apex’ starts at the 7th index.

contains()

contains() checks if a string contains a specified sequence of characters, returning true if it does, false if it doesn’t.


String str = 'Hello, Apex World!';
Boolean isPresent = str.contains('Apex');

In this case, isPresent is true.

startsWith(), endsWith()

startsWith() and endsWith() respectively check if a string begins or ends with a specified substring.


String str = 'Hello, Apex World!';
Boolean starts = str.startsWith('Hello');
Boolean ends = str.endsWith('World!');

Here, both starts and ends are true.

lowerCase(), upperCase()

These methods transform a string into all lowercase or all uppercase.


String str = 'Hello, Apex World!';
String lowerStr = str.toLowerCase();
String upperStr = str.toUpperCase();

lowerStr is 'hello, apex world!' and upperStr is 'HELLO, APEX WORLD!'.

replace(), replaceAll()

replace() substitutes all occurrences of a specified character sequence. replaceAll() does the same but accepts a regular expression as the first parameter.


String str = 'Hello, Apex World!';
String rplcStr = str.replace('Apex', 'Salesforce');

rplcStr is now 'Hello, Salesforce World!'.

valueOf

valueOf() converts different types (like Integer, Boolean, and more) to a string.


Integer num = 123;
String valStr = String.valueOf(num);

Here, valStr equals 123.

charAt()

charAt(index) retrieves a character from a specified index.


String str = 'Hello, Apex World!';
char chr = str.charAt(0);

Here, chr equals H.

equals()

equals() checks if two strings are identical, returning true if they are.


String str1 = 'Hello, Apex World!';
String str2 = 'Hello, Apex World!';
Boolean isEqual = str1.equals(str2);

In this case, isEqual is true.

remove()

remove() eliminates all occurrences of a specified sequence of characters from the string.


String str = 'Hello, Apex World!';
String remStr = str.replace('Apex', '');

Here, remStr is 'Hello, World!'.

reverse()

reverse() returns a string with the order of the characters reversed.


String str = 'Hello, Apex World!';
String revStr = str.reverse();

revStr is ‘!dlroW ,xepA ,olleH‘.

trim()

trim() drops the leading and trailing whitespace from a string.


String str = '    Hello, Apex World! ';
String trimStr = str.trim();

Here, trimStr is 'Hello, Apex World!'.

These are some of the most commonly used string methods in Apex. Mastering these will give you a significant edge when manipulating strings in your code.

Mastering String Manipulation Techniques

In Apex, one of the foundational skills every developer must master is string manipulation. Providing efficient solutions for various tasks like user input validation, data processing, and string formatting, these techniques should be in every Apex developer’s toolbox.

String Concatenation / Append

String concatenation is about joining strings using the + operator. Below is an example:


String greeting = 'Hello';
String target = 'World';
String message = greeting + ' ' + target;

In this example, message will hold the value “Hello World.”

String Escape Sequences

Escape sequences represent special characters in a string. They are important in formatting output properly, especially when dealing with special characters. Here’s how you use them:

String exampleStr = "Hello \"World\"";

The \" escape sequence includes the double-quote character in the string.

Multi-line Strings

Multi-line strings greatly help in formatting string outputs for easy reading, especially for big chunks of text:

String multiLineStr = 'Line 1\nLine 2\nLine 3';

Using the \n escape sequence, you can break down your string data into multiple lines.

String Cleansing

Removing special characters and whitespace within a string is especially useful during data pre-processing. Let’s see how to do this in Apex:


String dataWithSpecialChars = 'H!e#l$l%o W*o(r)l^d';
String cleanedData = dataWithSpecialChars.replaceAll('[^\\w\\s]', '');

In this example, cleanedData will hold the “Hello World” value after all special characters are removed.

To remove whitespaces:


String dataWithSpaces = 'Hello World';
String dataNoSpaces = dataWithSpaces.replaceAll('\\s+', '');

The replaceAll() function replaces all whitespace occurrences in the string with nothing.

Note: Ensuring clean and uniform data string is crucial in various scenarios like data analysis and record identification.

String Join

String join can be helpful when you have multiple items that need to be combined into one readable string:


List wordsList = new List{'Hello', 'World'};
String sentence = String.join(wordsList, ' ');

In this scenario, joining the various strings in wordsList forms the coherent sentence “Hello World”.

Accessing and Modifying String Characters

Working with individual characters in a string is common for tasks requiring precise string modifications or interpreting user inputs:


String str = 'Hello';
Character firstChar = str.charAt(0);

To remove the last character:


String str = 'World';
String newStr = str.substring(0, str.length() - 1);

To replace a character:


String str = 'Hello World';
String replacedStr = str.replace('W', 'w');

Use these techniques to gain finer control and flexibility over your string data.

You can handle and work with strings effortlessly in your Apex code by mastering these string manipulation techniques. Keep practising these techniques to become more proficient in manipulating string data in Salesforce, providing tailored solutions for any problem.

Mastering such techniques enables the elegant handling of common real-life problems in Apex development. Hence, it’s a must-have skill set for every Salesforce developer.

As we explore further sections, understand the importance of each technique while practising and make your string manipulations in Apex more efficient and elegant.

String Comparison

Now, let’s delve into various aspects of comparing strings in Apex:

String Null or Empty

Sometimes, you need to check if a string is null or empty. Here’s how you can do it:


String str = '';
if (String.isEmpty(str)) {
    System.debug('String is empty or null');
}

String isBlank vs isEmpty

Apex provides two methods to check if a string is empty – isBlank and isEmpty.

isEmpty() returns true if the string is null or an empty string (”). But isBlank() will also return true if the string only contains whitespace characters:


String str1 = '';
String str2 = ' ';
System.debug(String.isEmpty(str1)); // true
System.debug(String.isEmpty(str2)); // false
System.debug(String.isBlank(str1)); // true
System.debug(String.isBlank(str2)); // true

Compare Strings

You can use the equals() method to compare two strings. Take note it’s case-sensitive. Use equalsIgnoreCase() for case-insensitive comparison:


String str1 = 'Hello';
String str2 = 'hello';

System.debug(str1.equals(str2)); // false
System.debug(str1.equalsIgnoreCase(str2)); // true

String Length

To find the length of a string, use the length() method:


String str = 'Hello World';
System.debug(str.length()); // 11

These comparison techniques are essential for comparing and validating string data in Salesforce. Understanding these can enhance your Apex code’s reliability and robustness.

Data Conversion

Handling data types is a fundamental skill in programming, and Apex is no exception. Sometimes, you’ll need to convert data from one type to another to meet specific requirements. So, let’s explore how to execute these conversions proficiently in Apex.

String to Boolean

If you have a string that you know is either ‘true’ or ‘false’, this conversion is straightforward:


String boolStr = 'true';
Boolean boolVal = Boolean.valueOf(boolStr); // true

String to Number

To convert a string to a number, use the Integer.valueOf() or the Decimal.valueOf() method for integers or decimal numbers, respectively:


String numStr = '123';
Integer numVal = Integer.valueOf(numStr); // 123

Integer to String

The reverse is also simple. You can convert an integer to a string using the String.valueOf():


Integer num = 123;
String numStr = String.valueOf(num); // "123"

Date to String

When you want to convert a date to a string, the format of the string is yyyy-MM-dd:


Date myDate = Date.newInstance(2021, 11, 15);
String dateStr = String.valueOf(myDate); // "2021-11-15"

DateTime to String

Datetime to string conversion works similarly but includes time information:


Datetime now = Datetime.now();
String nowStr = String.valueOf(now);

String to Date

To convert a string back to a date, you can use the Date.parse() method:


String dateStr = '2021-11-15';
Date dateVal = Date.parse(dateStr);

Blob to String

A Blob represents binary data. Converting a Blob to a string requires the toString() method:


Blob b = Blob.valueOf('hello world');
String s = b.toString(); // "hello world"

Decimal to String

A decimal value to string follows the same pattern as the integer using the String.valueOf() method:


Decimal dec = 123.45;
String decStr = String.valueOf(dec); // "123.45"

ID to String

This is a simple one-to-one conversion using the String.valueOf() method again:


Id myId = '0011r00002IY4hMAAT';
String idStr = String.valueOf(myId);

Enum to String

Enums, or enumerated types, can be converted to strings using the name() method:


enum Color {RED, GREEN, BLUE}
Color myColor = Color.RED;
String colorStr = myColor.name(); // "RED"

List to String

With a list, you can join all elements into a single string using the String.join() method:


List myList = new List{'Apple', 'Banana', 'Cherry'};
String listStr = String.join(myList, ', '); // "Apple, Banana, Cherry"

Object to String

For object to string conversion, you would typically create a custom toString() method in your class:


public class MyObject {
    public String toString() {
        return 'This is my object.';
    }
}

MyObject obj = new MyObject();
String objStr = obj.toString();

These conversion methods prove to be a powerful tool in your Apex arsenal. As you can see, the Apex String class offers a variety of options to manage data conversions safely and efficiently. Understanding these will open a wider range of opportunities to handle various data types in your Apex code effectively.

Wrapping Up!

There you have it – our complete guide to taming string manipulation in Apex! We’ve covered a tremendous amount of ground here. At this point, you should feel empowered to wield strings with finesse to enhance your Salesforce coding chops.

You’re now equipped with an indispensable Apex string cheat sheet. You have critical techniques like splitting, concatenating, and validating strings at your fingertips. Also, you understand real-world applications like sanitizing inputs, generating dynamic text, and flexible data conversions using strings. Leverage these best practices to create lean, scalable code that makes teammates marvel.

I sincerely hope you found this guide valuable! Did I miss something? I welcome your intriguing string tips and constructive feedback in the comments.

So go ahead and share this with your teammate who’s been struggling with JSON parsing! If you get value from this, they will find it useful, too.

Leave a Comment