Find the length of string in apex

To find the length of a string in apex, you can use the length() function, which returns an integer. The length() method is used to validate the length of an input string to prevent saving records that exceed certain limits.

For example, to prevent users from storing email addresses longer than 80 characters, the length function can be used.

Length of string


Characters:

H
e
l
l
o
W
o
r
l
d
!

Index positions:

0
1
2
3
4
5
6
7
8
9
10
11

Length: 12 characters

Following is a sample code for finding the length of the above string in apex

Loading...

In the above example:

  • In the above example, inputString, is a string variable with the default value 'Hello World'.
  • The length() method is used to find the length of the string.
  • The string length() function returns an integer number, the length of the string.

Try It Yourself

Loading...