Previous Page
Next Page

16.4. String Processing

A string is a continuous sequence of characters terminated by '\0', the string terminator character. The length of a string is considered to be the number of characters before the string terminator. Strings are stored in arrays whose elements have the type char or wchar_t. Strings of wide charactersthat is, characters of the type wchar_tare also called wide strings .

C does not have a basic type for strings, and hence has no operators to concatenate, compare, or assign values to strings. Instead, the standard library provides numerous functions, listed in Table 16-16, to perform these and other operations with strings. The header string.h declares the functions for conventional strings of char. The names of these functions begin with str. The header wchar.h declares the corresponding functions for strings of wide characters, with names beginning with wcs.

Like any other array, a string that occurs in an expression is implicitly converted into a pointer to its first element. Thus when you pass a string as an argument to a function, the function receives only a pointer to the first character, and can determine the length of the string only by the position of the string terminator character.

Table 16-16. String-processing functions

Purpose

Functions in string.h

Functions in wchar.h

Find the length of a string.

strlen( )

wcslen( )

Copy a string.

strcpy( ), strncpy( )

wcscpy( ), wcsncpy( )

Concatenate strings.

strcat( ), strncat( )

wcscat( ), wcsncat( )

Compare strings.

strcmp( ), strncmp( ), strcoll( )

wcscmp( ), wcsncmp( ), wcscoll( )

Transform a string so that a comparison of two transformed strings using strcmp( ) yields the same result as a comparison of the original strings using the locale-sensitive function strcoll( ).

strxfrm( )

wcsxfrm( )

In a string, find:

  

  • The first or last occurrence of a given character

strchr( ), strrchr( )

wcschr( ), wcsrchr( )

  • The first occurrence of another string

strstr( )

wcsstr( )

  • The first occurrence of any of a given set of characters

strcspn( ), strpbrk( )

wcscspn( ), wcspbrk( )

  • The first character that is not a member of a given set

strspn( )

wcsspn( )

Parse a string into tokens

strtok( )

wcstok( )



Previous Page
Next Page