Developers

Salesforce String Class: Complete Guide & Tutorial

By Atlas Can

In programming, we often need to read and manipulate text inputs. Text in programming tends to be universally stored in the String data type and treated as an array of characters. This approach helps us construct the very fundamentals of the String class, and facilitate the operations we do on Strings.

In this article, we will give you the complete guide to String class in Salesforce, as well as a tutorial to help you get started!

What Is a String Class in Salesforce?

Apex identifies many field types as Strings in Salesforce, including but not limited to: texts, text areas, long and rich text areas, picklists, and email fields. Since they store text values, the names of records on Salesforce are considered Strings according to Apex.

Therefore, it is apparent that there is a requirement for standard predefined methods to gather and modify data, decreasing the need for code maintenance and increasing reusability. In Apex, these methods are combined under the String class.

String class is a predefined class variable in Apex which includes various methods that can perform useful operations on fields perceived as Strings. Since String exclusively means text in the Apex context, these methods can be performed on any field that stores text. 

String Class Examples and Methods

contains: Returns true if the String that called the method includes the given substring.

String str1 = 'Salesforce Ben';
String str2 = 'Salesforce';
System.assert(str1.contains(str2));

indexOf: Returns the starting index of the substring in the String that called the method.

String str = 'Salesforce Ben';
System.assertEquals(str.indexOf('force'), 5);

charAt: Returns the corresponding Unicode value of the character at a specified index of the

string that called the method.
String str = 'Salesforce Ben';
System.assertEquals(str.charAt(4), 115);

equals: Returns true if the String that called the method is identical to the parameter. This method is case sensitive.

String str1 = 'Salesforce';
String str2 = 'Salesforce';
System.assert(str1.equals(str2));

equalsIgnoreCase: Similar to the equals method but is case insensitive.

String str1 = 'Salesforce';
String str2 = 'SalesForce';
System.assert(str1.equalsIgnoreCase(str2));

startsWith & startsWithIgnoreCase: Return true if the String that called the method starts with the parameter. The methods are respectively case sensitive and case insensitive.

String str1 = 'Salesforce';
String str2 = 'Sales';
String str3 = 'SALES';
System.assert(str1.startsWith(str2));
System.assert(str1.startsWithIgnoreCase(str3));

isAlpha, isAlphaSpace, isAlphanumeric, isAlphanumericSpace: Respectively return true if the given String consists of: Unicode letters, Unicode letters and spaces, Unicode letters and numbers, Unicode letters and numbers and spaces.

String str = 'Salesforce';
System.assert(str.isAlpha());
System.assert(str.isAlphaSpace());
System.assert(str.isAlphanumeric());
System.assert(str.isAlphanumericSpace());

substring: Returns the substring between a start index and an end index of the String. If the end index is not given, the substring is assumed to be from the start index to the end of the String itself.

String str = 'Salesforce';
System.assertEquals(str.substring(0, 5), 'Sales');

isBlank, isNotBlank: The former returns true if the given String is null or blank, while the latter does the exact opposite. Keep in mind that this method is called from the String class itself rather than an instance of it.

String str1 = 'Salesforce';
String str2 = '';
System.assert(String.isNotBlank(str1));
System.assert(String.isBlank(str2));

valueOf: Converts the given value into a String. This method is also called from the String class.

Integer i = 4;
Boolean bool = false;
System.assertEquals(String.valueOf(i), '4');
System.assertEquals(String.valueOf(bool), 'false');

String Class Use Cases and Best Practices

Since gathering data from and doing operations on texts covers a broad array of tasks, so do the use cases of String class. Such cases include prohibiting null values for text fields in Apex integration services, making a decision based on whether a string contains a substring, enforcing rules on passwords, and so on. String class may also work in tandem with Apex triggers to put additional rules on records.

You can also use various String methods to convert 18-character IDs to 15-character IDs – Salesforce UI returns object IDs with 18 characters, however, returning values from the Salesforce API returns 15 characters:

CustomField__c = String.valueOf(obj.id).substring(0,15);

Since the Spring ’21 release, you have been able to use the System.Id class to15( ) method:

String Id_15_char = '0D5B000001DVM9t';
String Id_18_char = '0D5B000001DVM9tkAh';
ID testId = Id_18_char;
System.assertEquals(testId.to15(),Id_15_char);

Since picklist values are also represented as String variables in Apex, all manipulation techniques hold while working with picklist values as well. However, they require more care than regular text fields, as the transaction will fail if a picklist value that is option-restricted is assigned a value that is not in the value list. To see the values that a picklist allows, you can use the getPicklistValues() method:

public List<String> getPickListValuesIntoList(){
   	List<String> pickListValuesList= new List<String>();
    	Schema.DescribeFieldResult fieldResult = ObjectApiName.FieldApiName.getDescribe();
    	List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
    	for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
    	}    
    	return pickListValuesList;
	}

As we can see, there are a lot of use cases for String class, both for its data storing capabilities and its data manipulation techniques.

Since you will get to use the String class frequently (due to its prevalence among the data types in Salesforce), you should also take naming conventions into consideration. A String named a or str will not be descriptive enough for your code to be understood.

However, if these variables are named more descriptively, such as customerName and company, those who work on the code can get a clearer picture of what the variable is for, and whether it is a picklist value or standard text. The usefulness of naming conventions is true for every variable type in Apex, but you should be extra careful with Strings due to the wide usage.

Summary

String class and methods are common and make up the fundamental building blocks of Salesforce Developers’ Apex code. You will be using them daily, so it’s important to discover which method to use and how to use this data type efficiently. It’s also important to know that you do not need to know these methods by heart, as you will be discovering them on a case-by-case basis.

Thanks for reading and I hope you enjoyed this post! If you’re a Salesforce enthusiast like me, you will probably like my newest project, Blue Canvas, where we build modern CI, source control, and no-nonsense release management for Salesforce. We are aiming for a single unified platform that makes the whole team happy – admins, developers, and release managers!

You should also check out the Salesforce CPQ deployer tool which lets you ship a whole CPQ project without any SOQL knowledge.

The Author

Atlas Can

Atlas works as a 10x certified Salesforce Developer at Omnivo Digital and active on communities including his community SFDX.

Comments:

    Yes No Wheel
    February 01, 2023 12:19 am
    This is a great guide and tutorial on the Salesforce String Class. I have been using this class for a while now and it has been a great addition to my Salesforce toolkit.

Leave a Reply