Sage-Code Laboratory
index<--

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:

/* initialize a string: test */
char test[10] = {'t','e','s','t','\0'};
/* using string literal */
char test[] = "test";

Functions

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

Function Description
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:

#include <stdio.h>
#include <string.h>
int main () {
    char hello[] = "Hello ";
    char world[] = "World ";
    char both[24];
    int len ;
    /* copy hello to both */
    strcpy(both, hello);
    printf("strcpy(both, hello): %s\n", both );
    /* concatenates str1 and str2 */
    strcat( both, world);
    printf("strcat(both, world): %s\n", both );
    /* total length of both after concatenation */
    len = strlen(both);
    printf("strlen(both) : %d\n", len );
    return 0;
}

Output:

strcpy(both, hello): Hello
strcat(both, world): Hello World
strlen(both) : 12

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

#include <stdio.h>
int main()
{
    char s[1000];
    int i;
    printf("Enter a string: ");
    scanf("%s", s);
    for(i = 0; s[i] != '\0'; ++i);
    printf("Length of string: %d", i);
    return 0;
}

Read next: Bubble Sort