How to Find the Length of a String in Apex in Salesforce (With Examples & Use Cases)

In Salesforce Apex, working with strings is very common when handling user input, validating data, or processing records. One of the most basic but important operations is finding the length of a string.

Developers often need to check how many characters are present in a string to apply validations, conditions, or business logic.

While working as a Salesforce developer, I had to add a limitation for a custom field in the Case object. In limitation, the field should not exceed 200 characters. If the field exceeds this limit, the user will be notified to take other action, such as shutting down information.

To check whether the field exceeds the limit, we need to know the string’s length. I used the built-in apex length function to find this.

In this Salesforce tutorial, I will explain the various methods for determining a string’s length in Salesforce Apex.

What is a String in Apex?

A string in Apex is a sequence of characters. It can include letters, numbers, and special characters. Strings are widely used in Salesforce to store names, email addresses, addresses, and other text data.

For example:

  • “Salesforce”
  • “Hello World”
  • “admin@example.com”

Each string has a length, which represents the total number of characters in it.

Find the Length of a String in Apex in Salesforce

To find the string length in Salesforce Apex, navigate to the developer console and follow the steps below.

  1. Launch the anonymous window from Debug > Open Execute Anonymous Window in the developer console.
    • Enter the code below in the anonymous window, enter the code below, and click Execute.
String lenString = 'Find the length of the string';
Integer stringLength = lenString.length();
System.debug('The length of the string is: ' + stringLength);
  1. In the execution log window, select the checkbox to debug only. After this, you will see the length of the string characters in the debug.
Find the Length of a String in Apex in Salesforce

This way, we can use the length() function to get the string length in Salesforce Apex.

Find the Partial Length of the String Using Apex in Salesforce

Partial length means that a specific part of the string is selected. We can find the partial string length in Salesforce Apex using the substring() method.

For example, I have to calculate the string length of a paragraph, excluding the header and footer. For that, I will exclude the first ten and last ten characters from calculating the overall length.

Now, follow the steps below to find the length of a partial string in Salesforce Apex.

  1. Open the developer console and launch the Apex Anonymous Window with “Ctrl+E.”
    • Enter the code below in the developer console and click the Execute button.
String parString = 'Find the partial length of string';
Integer endIndex = parString.length() - 5;
Integer stringLength = parString.substring(5, endIndex).length(); 
System.debug('Partial Length: ' + stringLength);

In the above code, we have excluded the first five and last five characters from the string length calculation.

  1. In the Execution Log window, select the checkbox to debug only. Then, in the debug output, you will see the partial length of the string.
Calculate partial length of string in Salesforce apex

Following the steps above, we can calculate the partial length of a string in Salesforce Apex.

Calculate the String Length of only characters in Salesforce Apex

In Salesforce Apex, we can also calculate the length of only characters in a specific string. We can achieve this using the length() and replace() functions.

The output will only display the length of characters in the string, excluding the spaces and special characters.

Now, open the Salesforce developer console and follow the steps below.

  1. In the developer console, open the anonymous apex window using the shortcut key “Ctrl+E.”
    • Enter the code below in the anonymous window and click the Execute button.
String parString = 'Boost CRM growth: Automate #sales with @Salesforce!';
String onlyAlphabets = parString.replaceAll('[^a-zA-Z]', '');

Integer characterCount = onlyAlphabets.length();
System.debug('Actual length:'+ parString.length());
System.debug('Number of Characters: ' + characterCount);

In the above code, parString.replaceAll(‘[^a-zA-Z]’, ”) will remove all the non-alphabets from the string. Then, the length function will calculate the length of the alphabet (characters) in the string.

Here, I have displayed debug output for the actual length of the string and the length of its characters.

  1. In the execution log window, select the checkbox to debug only. Then, you will see the actual length of the string and the length of only the characters in the string.
Find length of String with characters in Salesforce Apex

In the debug console, we can see the actual length of the string and the length after removing special characters and spaces.

Length vs Size in Salesforce Apex

Many beginners get confused between:

  • length() → for String
  • size() → for List

Example:

List<String> names = new List<String>{'A', 'B', 'C'};
System.debug(names.size()); // Output: 3

Use:

  • length() for string
  • size() for collections

Conclusion

Finding the length of a string in Apex is a simple but very important concept. It helps developers validate data, control input, and build strong business logic in Salesforce applications.

By using the length() method correctly, along with null checks and best practices, you can avoid errors and improve your code quality.

If you are learning Salesforce Apex, mastering string operations like length() is essential because they are used in almost every real-world project. Practice with examples and try implementing these concepts in triggers and classes to gain confidence.

You may also like to read.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.