SaasGuru Logo

Flat 20% OFF on Salesforce Marketing Cloud and Data Cloud + AI Bootcamp 🎉– Offer Ends 30th Nov!

Flat 20% OFF on Salesforce Marketing Cloud and Data Cloud + AI Bootcamp 🎉– Offer Ends 30th Nov!
String Class in Salesforce

Understanding the String Class in Salesforce [With Examples]

Are you a Salesforce developer looking to master the String class and take your skills to the next level? Look no further! The String class is one of the most important concepts in Salesforce, allowing you to manipulate text and work with data in powerful ways.

In this detailed guide, we will cover everything you need to know about the String class in Salesforce. We’ll start from the basics, such as declaring a string variable, and gradually progress to more advanced topics, including complex string operations. 

Throughout the guide, we’ll explain the most commonly used string methods and provide practical examples to help you understand how to use them in your own Salesforce applications. Whether you’re new to Salesforce or an experienced developer, this guide will give you the knowledge and skills to become a string handling expert in Salesforce.

What is the String Class?

The Salesforce String class is essentially a data type that can be used to represent a string of characters. In Salesforce, strings can be found in a variety of contexts, from plain text fields to more advanced formula fields and Apex code. The ability to store and manipulate text-based data like names, locations, and descriptions is fundamental to many applications.

When you declare a string variable in Salesforce, you’re essentially creating a container for text data. You can then use various string methods to manipulate this data in different ways, such as adding or removing characters, converting cases, and more.

Since strings are immutable in Salesforce, their value cannot be changed once they are formed. Instead, a new string is created with the modified value when you perform a string that modifies the original string. It’s crucial to be conscious of how you use string methods in your code because of their possible impact on performance and memory consumption.

Also read, What is Apex Methods?

Salesforce String Variable Declaration Procedure

Strings in Salesforce are character sequences that are surrounded by double quotes. Alphanumeric information like names, addresses, and email addresses can all be saved in a string variable. 

The process for creating a string variable in Salesforce looks like this:-

Step 1: Open the Apex class or trigger where you want to declare the string variable.

Step 2: Declare the string variable using the syntax “String variableName; .”Here, “variableName” is the name you want to give to your string variable.

Step 3: Assign a value to the string variable using the syntax “variableName = ‘value’; .”Here, “value” is the alphanumeric data you want to store in your string variable.

Step 4: Alternatively, you can declare and initialize the string variable in a single line using the syntax “String variableName = ‘value’;.”

Step 5: You can also use the plus sign (“+”) as an operator to join multiple strings into a single one. For example, if you have two string variables named “firstName” and “lastName,” you can concatenate them to form a full name using the syntax “String fullName = firstName + ‘ ‘ + lastName;.”

Step 6: The square bracket notation is used to access the individual characters of a string. For example, if you have a string variable named “myString,” you can access the first character using the syntax “myString[0]”.

Step 7:To further format and manipulate the string data, a number of string methods are available. For example, you can convert a string to uppercase using the “toUpperCase()” method, or you can split a string into an array of substrings using the “split()” method.

salesforce certification courses for your team

What are String Methods?

In Salesforce, String methods are a set of built-in functions that allow developers to manipulate and modify string values. These techniques can reduce complexity, boost performance, and enhance the user’s entire encounter.

There are numerous string methods available in Salesforce, including functions for converting strings to lowercase or uppercase, removing whitespace, finding and replacing characters or substrings, and much more. 

Some of the typically used string methods in Salesforce include:-

List of String Class Methods

  1. toUpperCase()– Using this approach, a string can be made all caps. It is useful when you want to standardize the case of your string data, such as when comparing or sorting strings.

For Example, String myString = ‘hello world’; String upperString = myString.toUpperCase(); System.assertEquals(‘HELLO WORLD’, upperString);

  1. toLowerCase() – Use this function to make a string appear in lowercase. Like toUpperCase(), it is helpful when you want to standardize the case of your string data.

For Example, String myString = ‘HELLO WORLD’; String lowerString = myString.toLowerCase(); System.assertEquals(‘hello world’, lowerString);

  1. trim() – Whitespace at the beginning and end of a string is eliminated by this approach. It is useful when you want to remove any extra spaces or tabs that may be present in your string data.

For Example: String myString = ‘ hello world ‘; String trimmedString = myString.trim(); System.assertEquals(‘hello world’, trimmedString);

  1. substring() – This approach takes a string and returns a substring between the given start and finish points. It’s advantageous when you only need a portion of a longer string, such as a name or email address, to function.

For Example, String myString = ‘hello world’; String subString = myString.substring(0, 5); System.assertEquals(‘hello’, subString);

  1. replace() – This method allows you to alter the value of single or multiple occurrences of a substring. When working with string data, it’s helpful when you need to swap out certain characters or words.

For Example, String myString = ‘hello world’; String replacedString = myString.replace(‘world’, ‘there’); System.assertEquals(‘hello there’, replacedString);

  1. indexOf() – The first occurrence of a given substring within a string is returned by this method. It helps when looking for a specific piece of text within a longer string.

For Example, String myString = ‘hello world’; Integer index = myString.indexOf(‘world’); System.assertEquals(6, index);

  1. lastIndexOf() –This function returns the position of the last occurrence of a specified substring within a string. Finding the last occurrence of a substring within a larger string is facilitated by this method.

For Example, String myString = ‘hello world’; Integer lastIndex = myString.lastIndexOf(‘l’); System.assertEquals(9, lastIndex);

  1. startsWith() – This function always returns true if the specified substring is the first character of the string and false otherwise. It is very useful for checking if a string starts with a certain word or character.

For Example, String myString = ‘hello world’; Boolean startsWithHello = myString.startsWith(‘hello’); System.assertEquals(true, startsWithHello);

  1. endsWith() – This function will give back true if the string terminates with the given substring and false otherwise. You can use it to see if a string finishes with a specific word or character.

For Example, String myString = ‘hello world’; Boolean endsWithWorld = myString.endsWith(‘world’); System.assertEquals(true, endsWithWorld);

  1. split() – The string is split into an array of substrings using the separator you designate. When processing a comma-separated list, for example, it is helpful to be able to split a string into its component parts.

For Example, String myString = ‘hello,world’; List<String> myStringList = myString.split(‘,’); System.assertEquals(2, myStringList.size()); System.assertEquals(‘hello’, myStringList[0]); System.assertEquals(‘world’, myStringList[1]);

  1. concat() – Two or more strings can be joined using this approach. Joining strings is helpful when you need to create a longer string from several smaller ones.

For Example, String hello = ‘hello’; String world = ‘world’; String concatenatedString = hello.concat(world); System.assertEquals(‘helloworld’, concatenatedString);

  1. length() – The approach’s value for return is the string’s length. When counting the characters in a string, it becomes extremely useful.

For Example, String myString = ‘hello world’; Integer length = myString.length(); System.assertEquals(11, length);

  1. valueOf() – This function takes an input of a different data type and returns the input as a string. It is helpful, for instance, when you wish to turn a number or date into a string.

For Example: 

  • For date: Date myDate = Date.today(); String sD = String.valueOf(myDate); System.assertEquals(‘2023-04-10’, sD); 
  • For datetime: DateTime dt = datetime.newInstance(1995, 2, 25); String sDT = String.valueOf(dt); System.assertEquals(‘1995-02-25 00:00’. sDT);
  • For integer Integer myInt = 123; String sI = String.valueOf(myInt); System.assertEquals(‘123’, sI);
  • For decimal Decimal myDecimal = 123.45; String sDec = String.valueOf(myDecimal); System.assertEquals(‘123.45’, sDec);
  • For boolean Boolean myBool = true; String sBool = String.valueOf(myBool); System.assertEquals(‘true’, sBool);
  • For sObject record Id Account acc = new Account(Name=’Test Account’); insert acc; String sId = String.valueOf(acc.Id); System.assertEquals(acc.Id, sId);

Some Common String Literals

Salesforce also allows for several more specialized forms of string literals, such as:

  1. Escape Sequences: These are special characters that represent non-printable characters, such as newline (‘\n’) or tab (‘\t’).

For example: String myString = ‘First Line\nSecond Line’;

  1. Unicode Escapes: These are special character sequences that represent Unicode characters using their code points.

For example: String myString = ‘\u0041\u0042\u0043’;

In this example, the variable myString would contain the value ‘ABC’.

salesforce platform developer 1 bootcamp

Working with Strings in Salesforce

In Salesforce, Strings are used to store and manipulate text data. They can be concatenated, compared, and formatted to meet various business requirements. 

Let us discuss how to concatenate, compare, and format Strings in Salesforce.

1.Concatenating Strings in Salesforce

Concatenation is an essential operation when working with Strings in Salesforce. The “+” operator isn’t the only way to join strings together; the “concat()” function also works. 

For example:

String firstName = ‘John’;

String lastName = ‘Doe’;

String fullName = firstName.concat(‘ ‘).concat(lastName);

System.debug(fullName); // Output: John Doe

In this example, we have used the “concat()” method to concatenate two Strings “firstName” and “lastName” with a space character in between them to create a new String “fullName.”

The “+=” operator can also be used to attach a String to an already existing String. 

For example:

String message = ‘Hello’; message += ‘ World’;

System.debug(message); // Output: Hello World

In this example, we have used the “+=” operator to append the String ” World” to the existing String “Hello” to create a new String “Hello World”.

2. Comparing Strings in Salesforce

String comparison is a common operation when working with Strings in Salesforce. When comparing Strings, you can use either the “==” operator or the “equals()” method. 

For example:

String string1 = ‘hello’;

String string2 = ‘HELLO’;

if(string1.equals(string2)) { System.debug(‘Both strings are equal.’);

} else { System.debug(‘Both strings are not equal.’);

}

Here, the “equals()” method is used to check if “string1” and “string2” are the same. 

A message reading “Both strings are not equal” will be displayed if the Strings are not comparable.

We can use “equalsIgnoreCase()” to ignore case differences when comparing strings. 

For example:

String string1 = ‘hello’;

String string2 = ‘HELLO’;

if(string1.equalsIgnoreCase(string2)) { System.debug(‘Both strings are equal.’);

} else { System.debug(‘Both strings are not equal.’);

}

Strings “string1” and “string2” have been compared using the “equalsIgnoreCase()” method in this example. Given that both strings are identical, the result will simply read “Both strings are equal.

3. String Formatting in Salesforce

String formatting is a powerful feature when working with Strings in Salesforce. A String can be formatted in a number of ways, including with the “String.format()” method and the “printf()” method. 

For example:

String productName = ‘Widget’; Decimal productPrice = 10.50;

String productDescription = String.format(‘The price of %s is $%.2f.’, productName, productPrice);

System.debug(productDescription); // Output: The price of Widget is $10.50.

In this example, we have used the “String.format()” method to create a dynamic String “productDescription” with placeholders for the product name and price. The placeholders %s and %.2f are replaced with the values of “productName” and “productPrice” respectively.

We can also use the “printf()” method to format a String. For example:

String productName = ‘Widget’;

Decimal productPrice = 10.50;

System.debug(String.format(‘The price of %s is $%.2f.’, productName, productPrice)); // Output: The price of Widget is $10.50.

In this example, we have used the “printf()” method to create a dynamic String with placeholders for the product name and price. The placeholders %s and %.2f are replaced with the values of “productName” and “productPrice” respectively.

Advanced String Operations

As you continue to work with Strings in Salesforce, you may encounter more advanced scenarios that require additional operations. In this section, let us discuss three advanced String operations: regular expressions, handling HTML tags with Apex String class methods, and converting Strings to other data types.

1.Regular Expressions: Regular expressions, commonly referred to as regex, are powerful tools used to match, search, and manipulate strings. A pattern is defined by a string of characters and metacharacters. Apex’s Pattern and Matcher classes are responsible for the actual implementation of regular expressions.

Regular expressions are frequently used while validating data. For example, a valid email address or phone number will only accept entries that follow a specific format. 

Here’s some sample code to check if an email address is correct using regular expressions:

String email = ‘john.doe@example.com’;

String pattern = ‘[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}’;

Boolean isValid = Pattern.matches(pattern, email);

In this example, the pattern [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,} matches the standard format for an email address. The matches method returns true if the email variable matches the pattern, and false otherwise.

2. Apex String Class Methods for Handling HTML Tags: When working with HTML, it is important to be able to extract or manipulate specific elements within the HTML document. Apex’s String class includes various methods that allow simple to alter HTML tags.

The substringBetween method is frequently used since it returns the substring between two tags. 

The following is an example of code that will pull the title from an HTML document:

String html = ‘<html><head><title>Example</title></head><body>Content</body></html>’;

String title = html.substringBetween(‘<title>’, ‘</title>’);

In this example, the substringBetween method returns the text “Example”, which is the content of the <title> tag.

Another useful method is replaceAll, which replaces all occurrences of a specified string or regular expression with a new string. Here is an example code that replaces all instances of the <br> tag with a newline character:

String html = ‘This is<br>a line<br>break’; String converted = html.replaceAll(‘<br>’, ‘\n’);

In this example, the replaceAll method replaces all occurrences of the <br> tag with a newline character (\n), resulting in the string “This is\na line\nbreak.”

3. Converting Strings to Other Data Types: Converting strings to other data types, such as integers or dates, is a common task in Apex. The String class provides several methods for converting strings to other data types.

The valueOf function is frequently used because it may transform a string into a certain data type. To illustrate how to do so, here is some sample code:

String numberString = ’42’;

Integer number = Integer.valueOf(numberString);

In this example, the valueOf method converts the string “42” to an integer data type, which is assigned to the number variable.

Another useful method is parse, which is similar to valueOf but does not require the data type to be specified. Here is an example code that converts a string to a date:

String dateString = ‘2022-05-16’;

Date date = Date.parse(dateString);

In this example, the parse method converts the string “2022-05-16” to a date data type, which is assigned to the date variable.

Summing Up

In conclusion, the String class is a fundamental concept in Salesforce that allows developers to manipulate text and work with data in powerful ways. By understanding the basics of declaring a string variable and concatenation, as well as the common string methods and advanced string operations, developers can create robust and efficient applications to meet their business needs.

By following the comprehensive guide provided in this article, developers can gain a deep understanding of the String class and its various methods, enabling them to take their string manipulation skills to the next level.

Looking to start your career in Salesforce as a developer? check out our instructor-led Salesforce Platform Developer 1 training with capstone projects.

You can also check out our self-learn Salesforce Platform Developer 1 Online Course to get a personalized study plan, free mock exams, quizzes, flashcards and much more.

If you want to explore more, sign up with the  saasguru community on Slack and interact with seasoned Salesforce professionals. 

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Salesforce Data Loader Errors: How to Identify and Fix Them

Learn how to identify, troubleshoot, and prevent common Salesforce Data Loader errors with actionable tips and best practices. Read now!

Humans of Salesforce – Mauricio Alexandre Silva

Discover Mauricio Alexandre Silva’s inspiring Salesforce journey, tips for success, and insights into the evolving ecosystem. Read now!

Salesforce India Achieves $1 Billion Revenue Milestone

Salesforce India achieves $1 billion revenue milestone, driven by AI, innovation, and digital transformation across industries. Read now!