Strings

What is a string?

  1. In C, a string is simply an array of type char.
    Declaring a string:
    char str_var[20];
    

  2. The above declaration creates a variable that can hold a string from 0 to 19 characters long.
    Initializing a string:
    char str_var[20] = "Text goes here";
    

  3. The above creates the following in memory:
    T e x t   g o e s   h e r e \0 ? ? ? ? ?

  4. The '\0' is a null character, and indicates the end of the string. The content following the null character is ignored by the string functions in C.
  5. Note: it is very important to understand that the assignment operator (=) can be used for initialization of a string, but it CANNOT be used to change the value of an existing string. This should be accomplished using the strcpy function, listed below.

Arrays of strings

  1. An array of strings can be a two dimensional array of characters where each row is one string.
  2. Below is an array of the days of the week:
    char days_week[7][10] = {"Monday", "Tuesday", "Wednesday", Thursday",
                             "Friday", "Saturday", "Sunday"};
    

  3. Such an array can hold 7 strings, each up to 9 characters long.

printf and scanf with strings

  1. printf recognizes strings with the use of the %s argument.
  2. To right-justify, place the minimum field width in the argument, such as %9s.
  3. To left-justify, add a "-", such as %-9s.
    Example:
    printf("__%-10s__%10s__\n","Text", "Text2");
    

    Results:
    __Text      __     Text2__
    

  4. With scanf, the %s argument is also used.
  5. With a string, no "&" is used.
    Example:
    char astring[20];
    int numb;
    
    scanf("%s", astring);
    scanf("%d", &numb);
    

Library functions for strings

Function Library Description
strcpy(s1, s2) string.h Copies the value of s2 into s1
strncpy(s1, s2, n) string.h Copies n characters of s2 into s1. Does not add a null.
strcat(s1, s2) string.h Appends s2 to the end of s1
strncat(s1, s2, n) string.h Appends n characters of s2 onto the end of s1
strcmp(s1, s2) string.h Compared s1 and s2 alphabetically;
returns a negative value if s1 should be first,
a zero if they are equal,
or a positive value if s2 sbould be first
strncmp(s1, s2) string.h Compares the first n characters of s1 and s2 in the same manner as strcmp
strlen(s1) string.h Returns the number of characters in s1 not counting the null

  1. strncpy can be used to extract substrings that begin in the middle of a string as well as the beginning.
  2. To do this, the s2 argument must be the specific memory address in which to begin copying.
    Example:
    char lastname[20];
    char name[10] = "Joe Bob";
    
    /* extract the last name into "lastname" */
    
    strncpy(lastname, &name[4], 3);
    lastname[3] = '\0';