As a full-stack developer well-versed in multiple programming languages, I often underestimate the power of strings in Apex code. The String class provides such a wide breadth of functions that strings act as a Swiss Army knife for text manipulation.

In this comprehensive 3200+ word guide, we will explore the intricate capabilities of strings and the String class in Apex. With code examples for standard and custom Salesforce objects, you will learn how to fully utilize strings to scale your automation, analytics, and processes on the Salesforce platform.

String Class Overview

The String class in Apex contains over 40 methods to transform, compare, and modify text values. From a high level, the core capabilities include:

  • Text Transformation: Changing cases, trimming, replacing substrings
  • Text Analysis: Checking equality, containment, starts/ends matching
  • Text Iteration: Looping through each character
  • Text Extraction: Substring, split by delimiter
  • Length Handling: Finding length, padding strings

With this broad set of functionalities, the String class allows concise manipulation of text-based data without needing to write lengthy code ourselves.

Underlying String Storage

Internally, the String class stores text data as immutable arrays of Unicode characters. This makes them more efficient for memory usage than mutable alternatives in languages like JavaScript.

We cannot directly access or modify the underlying character arrays. Instead, the String methods return new string values.

String original = ‘Salesforce‘; 

original[0] = ‘C‘; // Runtime error - cannot directly change

String changed = original.replace(‘Sales‘, ‘Cloud‘); // Create new string

String Pool

Apex also utilizes a string pool to optimize memory utilization for common values. Identical string literals point to a single instance.

For example:

String text1 = ‘Hello‘; 
String text2 = ‘Hello‘;

// text1 and text2 reference the SAME string from the pool 

This boosts efficiency in your code when reusing unchanging text like application constants.

Declaring and Assigning

To declare a string variable, we use the standard String syntax:

String myText;

We can immediately assign a value with a literal:

String firstName = ‘John‘; 

Or assign later in our logic:

String lastName;

// Code that sets value
lastName = ‘Doe‘; 

Using string literals should be minimized for common values that could change. Declaring constants is preferable:

static final String COMPANY_NAME = ‘Acme Corporation‘;

Concatenation

Combining strings together is straightforward with the + operator:

String firstName = ‘John‘;
String lastName = ‘Doe‘;

String name = firstName + ‘ ‘ + lastName;
// ‘John Doe‘

This provides readable in-line concatenation. However, for complex logic we should leverage String.format():

Decimal revenue = 10000;
String output = String.format(‘Revenue was {0}‘, revenue);

// ‘Revenue was 10000‘  

String.format() handles multiple data types and reuses the same string template.

Finding Length

To get the number of characters in a string use length():

String companyName = ‘Acme Corporation‘;
Integer length = companyName.length();
// Length: 16

Tracking string lengths aids input validation and remaining character counters.

Changing Case

When comparing strings or normalizing formats, case changes help match textual data.

String city = ‘Chicago‘;

String upper = city.toUpperCase(); 
// ‘CHICAGO‘

String lower = city.toLowerCase();
// ‘chicago‘  

This standardizes strings to apply case-insensitive evaluations.

Trimming Whitespace

Removing extra whitespace improves data consistency using trim():

String name = ‘     John Doe       ‘;
String trimmed = name.trim(); 
// ‘John Doe‘

Trimming should often occur when processing user-provided strings.

Replacing Substrings

To swap text segments out dynamically:

String message = ‘Hello {Name}!‘; 

String personalized = message.replace(‘{Name}‘, firstName);
// ‘Hello John!‘

Replacing enables string templates that work for all records.

Splitting Strings

To divide strings into reusable parts with split():

String fullName = ‘John Doe‘;

List<String> names = fullName.split(‘ ‘); 
// names[0] = ‘John‘
// names[1] = ‘Doe‘

The array output allows iteration and analysis on substrings.

Extracting Substrings

When needing to parse strings independently:

String data = ‘{Id:5675,Name:Acme}‘;

String recordId = data.substringBetween(‘{Id:‘, ‘,Name:‘); 
// ‘5675‘

String companyName = data.substringBetween(‘Name:‘, ‘}‘);
// ‘Acme‘ 

Substrings enable piecewise processing.

Finding Occurrences

Counting string matches with countMatches():

String summary = ‘The sales team closed 12 new deals last month.‘;

Integer dealsCount = summary.countMatches(‘sales‘);
// 1

This quantifies trends for analytics on long text values.

Checking Equality

Comparing strings with equals signs:

if (firstName == ‘John‘) {
  // Name is John
}

Or inequality operator:

if (lastName != ‘Doe‘) {
  // Last name is NOT Doe
}

Equality helps validate correctness or find issues.

Contains Checking

Using includes() to validate substrings:

String fullname = ‘John Doe‘;

Boolean hasJohn = fullname.includes(‘John‘); // true

Contains flags partial matches for flexible validations.

Starts/Ends Validation

Matching prefixes/suffixes with startsWith() and endsWith():

String phone = ‘+1 333 555 1234‘; 

if (phone.startsWith(‘+‘)) {
  // Validate international 
}

if (phone.endsWith(‘#‘)) {
  // Check for extension
}

This detects patterns requiring certain beginnings or endings.

All Lower/Upper Case

Checking if a string matches a single case using isAllLowerCase() or isAllUpperCase():

String myText = ‘HelloWorld‘;

Boolean isLower = myText.isAllLowerCase(); // false 
Boolean isUpper = myText.isAllUpperCase(); // false

Matches force standardized casing when necessary.

Character Iteration

Looping each character with for loops:

String data = ‘1234‘;

for (Integer i = 0; i < data.length(); i++) {
  String char = data.mid(i, 1); 
  // 1st loop: ‘1‘ 
  // 2nd loop: ‘2‘
  // etc.
}

This expands processing and analysis capabilities per character.

Reversing Contents

Flip order with reverse():

String forward = ‘ABC‘; 

String backward = forward.reverse(); 
// ‘CBA‘

Reversing manipulates arrays, log files, names, etc.

String Builder

For complex string generation, .append() repeatedly:

StringBuilder output = new StringBuilder();

for (Account acct : accounts) {
  output.append(acct.Name + ‘\n‘); 
}

String data = output.toString();
// String with names separated by newlines 

This handles large outputs without performance issues.

Real-World Examples

Now let’s see some practical examples of utilizing strings and String methods within Salesforce automation:

Redact Sensitive Data

String data = ‘123456-7890‘;

data = data.replaceAll(‘[0-9]‘, ‘X‘);  
// ‘XXXXXX-XXXX‘

Extract Domain from Email

String email = ‘john@acme.com‘;

String domain = email.substringAfter(‘@‘);
// ‘acme.com‘

Generate Address Combinations

String street = ‘123 Main St‘; 
String city =  ‘Anytown‘;
String state = ‘CA‘;

List<String> addresses = new List<String>();

addresses.add(street + ‘, ‘ + city + ‘, ‘ + state);
addresses.add(city + ‘, ‘ + state + ‘ ‘ + street); 

// Returns address format permutations

Validate Credit Card Numbers

String ccNumber = ‘3455671881234‘;

Boolean isValid = ccNumber.length() == 16 && 
                  ccNumber.isNumeric(); 

Clean Imported Data

String row = ‘  John |Doe ‘; 

row = row.trim();
row = row.replace(‘|‘, ‘,‘);

// ‘John,Doe‘

Summary

The wide range of string handling and manipulation capabilities provided in Apex enables powerful text processing logic. With the String class, strings act as an invaluable toolkit for interacting with, analyzing, and converting text-based data.

Mastering the methods covered here allows mitigating input issues, finding hidden insights, automating record updates, and ultimately maximizing the value extracted from textual data enterprise-wide.

As a full-stack developer by trade, I used to underestimate just how expansive yet flexible capabilities for strings are within Apex and Salesforce. Hopefully this guide provided helpful clarity into how significant the String class is for any application.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *