num_bytes()

Return the length of a string in number of bytes.

Syntax

num_bytes( string , [num_chars])

Parameter

ParameterDefinition

string

text string whose final character is NULL

num_chars

maximum number of characters to count

Description

The num_bytes() function returns the number of bytes in a string. It differs from length(), which returns the number of characters. Due to international codesets, a single character can be composed of one or more bytes. 

This function counts all bytes in a string until it reaches the NULL character "", which causes the function to return the number of bytes it has counted. You can use the optional num_chars parameter to limit the number of characters that the function counts. For example, if num_chars is 20, num_bytes() returns 20 if the string is 20 characters or longer. It returns a number less than 20, however, if num_bytes() finds a NULL character before it counts the twentieth character.

Note

This function provides support for internationalized PSL scripts. For more information about internationalization, see Internationalized PSL Scripts.

The following example on shows that num_bytes() reads characters but returns bytes. The num_chars parameter has a value of 4, but num_bytes() returns 6. This difference exists because two of the characters are composed of two bytes.

Example

This example shows the num_bytes() function. 

# LANG = ja_JP.eucJP
function run_num_bytes(id, str, nchar){
ret = num_bytes(str, nchar);
printf("ID = %d, nchar = %d, return = %d\n", id, nchar, ret);
}
run_num_bytes("1", "", -1);
run_num_bytes("2", "", 0);
run_num_bytes("3", "", 1);
run_num_bytes("4", "a ", -1);
run_num_bytes("5", "a ", 0);
run_num_bytes("6", "a ", 1);
run_num_bytes("7", "a ", 2);
run_num_bytes("8", "¤Ò¤ç¤¼ ", -1);
run_num_bytes("9", "¤Ò¤ç¤¼ ", 0);
run_num_bytes("10", "¤Ò¤ç¤¼ ", 1);
run_num_bytes("11", "¤Ò¤ç¤¼ ", 2);
run_num_bytes("12", "¤Ò¤ç¤¼ ", 3);
run_num_bytes("13", "¤Ò¤ç¤¼ ", 4);
run_num_bytes("14", "¤Ò¤ç¤¼ ", 10);

The preceding example produces the following output: 

ID = 1, nchar = -1, return = 0
ID = 2, nchar = 0, return = 0
ID = 3, nchar = 1, return = 0
ID = 4, nchar = -1, return = 2
ID = 5, nchar = 0, return = 0
ID = 6, nchar = 1, return = 1
ID = 7, nchar = 2, return = 2
ID = 8, nchar = -1, return = 8
ID = 9, nchar = 0, return = 0
ID = 10, nchar = 1, return = 1
ID = 11, nchar = 2, return = 2
ID = 12, nchar = 3, return = 3
ID = 13, nchar = 4, return = 4
ID = 14, nchar = 10, return = 8

 

 

Related topics

PSL Built-in Functions

Developing

Was this page helpful? Yes No Submitting... Thank you

Comments