Menu Close

Articles

C: String functions

Strings are actually arrays of characters terminated by a null character ‘\0’.  Elements of the array can be modified, therefore a string is mutable, unlike Java strings that are immutable. However the capacity of a C string is fixed. If you wish to change the capacity you must move the string in a new memory location.

String Initialization

There are two ways to initialize a string: By using a string literal and by using the array literal. The string literal is an enumeration of characters enclosed in double quotes: “…”. The null character do not have to be specified, it is automatically added at the end of the string.

Examples:

Functions

To use string functions you must include header file: <string.h> 

FunctionDescription
strcpy(s1, s2)

Copies string s2 into string s1.

strcat(s1, s2)

Concatenates string s2 onto the end of string s1.

strlen(s1)

Returns the length of string s1.

strcmp(s1, s2)

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

strchr(s1, ch)

Returns a pointer to the first occurrence of character ch in string s1.

strstr(s1, s2)

Returns a pointer to the first occurrence of string s2 in string s1.

Example:

Output:

Note:

The capacity of string “both” is larger then the actual string. So there is an unused region of memory after “\0” for the string “both”. The len function will report only the used part and ignore the rest.

String traversal

Since a string is actually an array, we can traverse the string character by character. This may be useful if we wish to make modifications in the string. In example below we use this trick to find the length of a string without a function:

Example

Read next: Bubble Sort