%LEFT (Get Leftmost Characters)

%LEFT(string : length { : *NATURAL | *STDCHARSIZE } )

%LEFT returns the leftmost characters of a string.

The first operand is a string. It can be alphanumeric, graphic, or UCS-2.

The second operand is the number of characters to return.

The third operand can be specified to set the CHARCOUNT mode for the statement. See Example demonstrating the effect of the CHARCOUNT mode on %LEFT.
  • Specify *NATURAL as the third parameter for %LEFT to operate in CHARCOUNT NATURAL mode.
  • Specify *STDCHARSIZE as the third parameter for %LEFT to operate in CHARCOUNT STDCHARSIZE mode.
  • If the third parameter is not specified, %LEFT operates in the charcount mode for the statement as set by the CHARCOUNT Control keyword or the /CHARCOUNT directives.

When %LEFT is operating in CHARCOUNT NATURAL mode, the second operand refers to the number of characters to return.

When %LEFT is operating in CHARCOUNT STDCHARSIZE mode, the second operand is the number of bytes or double-bytes to return.

For more information, see String Operations and Built-in Functions.

Example of %LEFT

In the following example, the string begins with a name followed by a colon followed by more information. The programmer uses %LEFT to get the name.
  1. The %SCAN built-in function returns 11 for the position of the colon.
  2. The %LEFT built-in function returns "John Smith".

DCL-S string VARCHAR(1000);
DCL-S name VARCHAR(25);
DCL-S colon INT(10);

string = 'John Smith: 100, 500, 700';
colon = %SCAN(':' : string); //  1 
name = %LEFT(string : colon - 1); //  2 
// name = "John Smith"

Example demonstrating the effect of the CHARCOUNT mode on %LEFT

  • In the following example, the UTF-8 string "ábç" has three characters, but characters 'á' and 'ç' have two bytes each.
    1. %LEFT('ábç' : 2) returns 'áb' in natural mode.
    2. %LEFT('ábç' : 2) returns 'á' in stdcharsize mode.
    
    CTL-OPT CHARCOUNTTYPES(*UTF8);
    
    DCL-S string VARCHAR(10) CCSID(*UTF8);
    DCL-S left VARCHAR(10) CCSID(*UTF8);
    
    string = 'ábç';
    
    /CHARCOUNT NATURAL
    left = %LEFT(string : 2); //  1 
    // left = 'áb'
    
    /CHARCOUNT STDCHARSIZE
    left = %LEFT(string : 2); //  2 
    // left = 'á'