In Apex, surrogate pair characters are interpreted as a single character by combining a "high surrogate" and a "low surrogate". Therefore, if you use the substring(0, 1)` method on a String variable containing a single surrogate pair to extract only the high surrogate, Apex does not interpret the result as a valid surrogate pair, and the character cannot be retrieved correctly.
This article explains why the Apex String class substring method returns an invalid character when you extract a surrogate pair character, and how to retrieve the full character. This happens because the Apex substring method counts each surrogate (high and low) as a separate index position, even though they represent one visible character. To correctly retrieve a surrogate pair character, your code must grab both positions together.
Suppose a String variable `myStr` contains a single surrogate pair character (for example, certain emoji or rare CJK characters use surrogate pairs). The following Apex code calls substring with an end index of 1:
String result = myStr.substring(0, 1);
This code returns only the high surrogate half of the character, which is not valid on its own and does not display or compare correctly.
To retrieve the full character, include both the high and low surrogate by using an end index of 2 instead of 1. The following Apex code returns both surrogate values together:
String result = myStr.substring(0, 2);
This retrieves both surrogate values together, so the character is extracted correctly.
000395737

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.