C-help Logo Thursday, November 23, 2017
By The Voodooman faq | about

String Functions

Includes

#include <string.h>

The standard string functions that are available to a C programmer may seem a little strange if you are coming from a background of another language such as Visual Basic or Pascal. In particular, a lot of VB programmers have difficulty understanding why you should use strcpy to assign a value to a string variable, instead of assigning it directly (as in foo="the string";). However, it should not take you too long to understand the various C functions that are used to manipulate strings.

TOP


Assigning/Copying

In C, the process of assigning a string to a string variable consists of copying the value into a variable using a function. You cannot assign a string directly to a variable, since a string is an array. Hence you cannot do something like foo = "stringvalue";. Instead you must use a function to do your assignment. There are two functions that can be used for copying strings from the source to the destination. The thing to remember is to ALWAYS ensure that your destination array is large enough.


STRCPY(3) Linux Programmer's Manual STRCPY(3)

NAME

strcpy, strncpy - copy a string

SYNOPSIS

#include <string.h>

char *strcpy(char *dest, const char *src);

char *strncpy(char *dest, const char *src, size_t n);

DESCRIPTION

The strcpy() function copies the string pointed to be src (including the terminating `\0' character) to the array pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

The strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null byte among the first n bytes of src, the result wil not be null-terminated.

In the case where the length of src is less than that of n, the remainder of dest will be padded with nulls.

RETURN VALUE

The strcpy() and strncpy() functions return a pointer to the destination string dest.

BUGS

If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid/lazy, and failed to check the size before copying) then anything might happen. Overflowing fixed length strings is a favourite cracker technique.

CONFORMING TO

SVID 3, POSIX, BSD 4.3, ISO 9899

SAMPLE CODE

#include <stdio.h>
#include <string.h>

/*
* strcpy, strncpy demo
* Author:      Mayukh Bose
* Purpose:     To demonstrate the usage of strcpy and strncpy
* Description: The program copies the whole string and the first
*              5 characters alone and prints them both. It also
*              shows how to assign strings.
*/
int main() {
  char *source= "this is a test";
  char dest[100]; /* Make sure dest is large enough! */
  memset(dest, '\0', 100); /* Set it to all null chars to be sure */
  strcpy(dest, source);
  printf("Copied source to dest.\n");
  printf("Source: %s\nDest: %s\n", source, dest);

  /* Now assign dest to another string */
  strcpy(dest, "Another string");
  printf("Source: %s\nDest: %s\n", source, dest);
  /* Note: You cannot do this -
           dest = "Another string";
     This is an ERROR since "Another string" is a character array
     and so is dest. In order for it to work correctly, you must
     copy the contents into the dest array, one element at a time.
     This is what strcpy does for you.
  */

  /* Now copy only 5 chars from source to dest */
  memset(dest, '\0', 100); /* Set it to all null chars to be sure */
  strncpy(dest, source, 5);
  printf("Copied 5 chars from source to dest.\n");
  printf("Source: %s\nDest: %s\n", source, dest);
  
  return 0;
}

TOP

Finding

There are three functions that are usually used for locating characters or substrings within strings. The functions are strchr, strrchr and strstr. The purpose of these three functions is as follows:

  • strchr: Locate a single character in a string
  • strrchr: Same as above, except works backwards on the string.
  • strstr: Locates a substring (one or more characters) in a string. This is the function that you will use the most generally.

    There are also two other functions called index and rindex, whose syntax is virtually identical to strchr and strrchr respectively. These two function will therefore not be discussed here. Another function that is sometimes used is called strpbrk. This function works like strchr, except that it can be given multiple characters to search for. The documention for this function is presented here without any working code. Note that the code for this section is in two parts: The first one appears below the documentation for strchr and strpbrk and the second one appears below the documentation for strstr.

    STRCHR(3) Linux Programmer's Manual STRCHR(3)

    NAME

    strchr, strrchr - locate character in string

    SYNOPSIS

    #include <string.h>

    char *strchr(const char *s, int c);

    char *strrchr(const char *s, int c);

    DESCRIPTION

    The strchr() function returns a pointer to the first occurrence of the character c in the string s.

    The strrchr() function returns a pointer to the last occurrence of the character c in the string s.

    RETURN VALUE

    The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not found.

    CONFORMING TO

    SVID 3, POSIX, BSD 4.3, ISO 9899


    STRPBRK(3) Linux Programmer's Manual STRPBRK(3)

    NAME

    strpbrk - search a string for any of a set of characters

    SYNOPSIS

    #include <string.h>

    char *strpbrk(const char *s, const char *accept);

    DESCRIPTION

    The strpbrk() function locates the first occurrence in the string s of any of the characters in the string accept.

    RETURN VALUE

    The strpbrk() function returns a pointer to the character in s that matches one of the characters in accept, or NULL if no such character is found.

    CONFORMING TO

    SVID 3, POSIX, BSD 4.3, ISO 9899

    SAMPLE CODE

    #include <stdio.h>
    #include <string.h>

    /*
    * strchr, strrchr demo
    * Author:      Mayukh Bose
    * Purpose:     To demonstrate the use of strchr and strrchr
    * Description: The program uses the two functions to locate
    *              characters within a string.
    */
    int main() {
      char *haystack = "This is a very long string";
      char *needle = NULL;
      
      /* Try to locate the letter v */
      needle = strchr(haystack, 'v');
      if (needle)
        printf("Located letter v. Rest of string from point: %s\n", needle);
      else
        printf("Could not locate the letter v\n");

      /* Try to locate the letter l from the back*/
      needle = strrchr(haystack, 'l');
      if (needle)
        printf("Located letter l. Rest of string from point: %s\n", needle);

      /* Figure out the index of letter v */
      needle = strchr(haystack, 'v');
      if (needle)
          printf("Located letter v at %d\n", (int)(needle - haystack));
      
      return 0;
    }


    STRSTR(3) Linux Programmer's Manual STRSTR(3)

    NAME

    strstr - locate a substring

    SYNOPSIS

    #include <string.h>

    char *strstr(const char *haystack, const char *needle);

    DESCRIPTION

    The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating `\0' characters are not compared.

    RETURN VALUE

    The strstr() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.

    BUGS

    Early versions of Linux libc (like 4.5.26) would not allow an empty argument. Later versions (like 4.6.27) work cor­ rectly, and return haystack when needle is empty.

    SAMPLE CODE

    #include <stdio.h>
    #include <string.h>

    /*
    * strstr demo
    * Author:      Mayukh Bose
    * Purpose:     To demonstrate the usage of the strstr function
    * Description: The program uses strstr to locate one string within
    *              another one.
    */
    int main() {
      char *haystack = "Looking for a target in here";
      char *needle = "target";
      char *ptr = NULL;

      ptr = strstr(haystack, needle);
      if (ptr)
        printf("Found \"%s\" in \"%s\" at position %d\n", needle,
                  haystack, (int)(needle - haystack));
      else
        printf("Could not find \"%s\" in \"%s\"", needle, haystack);

      return 0;
    }

    TOP

    Length

    The function to find the length of a given string is called strlen. The function returns the length of the string, not the length of the array that contains it. Remember that if the string contains any null ('\0') characters in it, then the function returns the length upto the first null character alone.

    STRLEN(3) Linux Programmer's Manual STRLEN(3)

    NAME

    strlen - calculate the length of a string

    SYNOPSIS

    #include <string.h>

    size_t strlen(const char *s);

    DESCRIPTION

    The strlen() function calculates the length of the string s, not including the terminating `\0' character.

    RETURN VALUE

    The strlen() function returns the number of characters in s.

    CONFORMING TO

    SVID 3, POSIX, BSD 4.3, ISO 9899

    SAMPLE CODE

    #include <stdio.h>
    #include <string.h>

    /*
    * strlen demo
    * Author:      Mayukh Bose
    * Purpose:     To demonstrate the usage of the strlen function
    * Description: The program uses strlen to compute a string's length.
    */

    int main() {
      char *string1 = "This is a reasonably long string";
      char string2[80] = "This is another string in an 80 char array";
      char string3[80] = "This is a string\0 that contains nulls";
      int i;

      i = strlen(string1);
      printf("The length of \"%s\" is %d\n", string1, i);

      i = strlen(string2);
      printf("The length of string2 is %d\n", i);
      /* The length of string2 is the length of the string it contains,
         though the array can hold a lot more (up to 80 chars). */


      i = strlen(string3);
      printf("The length of string3 is %d because of the NULL char.\n",
                 i);
      /* Notice how string3 is truncated because of the null
         character that is embedded in the string. */

      return 0;
    }

    TOP

    Comparing

    There are four functions that are used to compare strings. Two are case-sensitive and two are not. The functions are:

  • strcmp: Compares two strings.
  • strncmp: Compares only the first 'n' characters of the two strings.
  • strcasecmp: Same as strcmp, except that this ignores case during the comparision.
  • strncasecmp: Same as strncmp, except that this ignores case during the comparision.

    Note that these functions all return a value that may be less than, equal to or greater than 0. If the value returned is less than zero, then the first string is less than the second string. If the value returned is greater than zero, then the first string is greater than the second string. If the value returned is zero, then the two strings are equal. There is also a fifth function called strcoll which compares strings according to locale settings. The arguments for this function are identical to strcmp.


    STRCMP(3) Linux Programmer's Manual STRCMP(3)

    NAME

    strcmp, strncmp - compare two strings

    SYNOPSIS

    #include <string.h>

    int strcmp(const char *s1, const char *s2);

    int strncmp(const char *s1, const char *s2, size_t n);

    DESCRIPTION

    The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

    The strncmp() function is similar, except it only compares the first n characters of s1.

    RETURN VALUE

    The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

    CONFORMING TO

    SVID 3, POSIX, BSD 4.3, ISO 9899


    STRCASECMP(3) Linux Programmer's Manual STRCASECMP(3)

    NAME

    strcasecmp, strncasecmp - compare two strings ignoring case

    SYNOPSIS

    #include <string.h>

    int strcasecmp(const char *s1, const char *s2);

    int strncasecmp(const char *s1, const char *s2, size_t n);

    DESCRIPTION

    The strcasecmp() function compares the two strings s1 and s2, ignoring the case of the characters. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

    The strncasecmp() function is similar, except it only com­ pares the first n characters of s1.

    RETURN VALUE

    The strcasecmp() and strncasecmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

    CONFORMING TO

    BSD 4.4

    SAMPLE CODE

    #include <stdio.h>
    #include <string.h>

    /*
    * strcmp, strncmp, strcasecmp, strncasecmp demo
    * Author:      Mayukh Bose
    * Purpose:     To demonstrate the usage of the strcmp, strncmp,
    *              strcasecmp and strncasecmp functions
    * Description: The program uses these functions to compare various
    *              strings to each other.
    */
    int main() {
      char *string1 = "This is a string";
      char *string2 = "This is also a string";
      char *string3 = "This is a string";
      char *string4 = "this is a string";

      int x;

      x = strcmp(string1, string3);
      if (x == 0)
        printf("String1 and string3 are equal.\n");
      else if (x < 0)
        printf("String1 is less that string 3.\n");
      else if (x > 0)
        printf("String1 is greater than string 3.\n");

      x = strncmp(string1, string2, 7);
      if (x == 0)
        printf("String1 and string2 are equal for the first 7 chars\n");
      else
        printf("String1 and string2 are not equal for the first 7 chars\n");

      x = strcmp(string1, string4);
      if (x == 0)
        printf("String1 and string4 are equal.\n");
      else
        printf("String1 is not equal to string4.\n");

      x = strcasecmp(string1, string4);
      if (x == 0)
        printf("string1 and string4 are equal (ignoring case)\n");

      x = strncasecmp(string2, string4, 7);
      if (x == 0)
        printf("string2 and string4 are equal for first 7 chars (ignoring case)\n");
      
      return 0;
    }

    TOP

    Appending/Joining

    There are two functions that are used to append/join strings together:
  • strcat: Concatenate two strings
  • strncat: Concatenate the first 'n' characters of one string to another.

    You can also use the sprintf function to concatenate various types into a string variable. The author personally uses sprintf as a personal preference.


    STRCAT(3) Linux Programmer's Manual STRCAT(3)

    NAME

    strcat, strncat - concatenate two strings

    SYNOPSIS

    #include <string.h>

    char *strcat(char *dest, const char *src);

    char *strncat(char *dest, const char *src, size_t n);

    DESCRIPTION

    The strcat() function appends the src string to the dest string overwriting the `\0' character at the end of dest, and then adds a terminating `\0' character. The strings may not overlap, and the dest string must have enough space for the result.

    The strncat() function is similar, except that only the first n characters of src are appended to dest.

    RETURN VALUE

    The strcat() and strncat() functions return a pointer to the resulting string dest.

    CONFORMING TO

    SVID 3, POSIX, BSD 4.3, ISO 9899

    SAMPLE CODE

    #include <stdio.h>
    #include <string.h>

    /*
    * strcat, strncat demo
    * Author:      Mayukh Bose
    * Purpose:     To demonstrate the usage of strcat and strncat
    * Description: The program concatenates various strings together
    *              and prints out the results.
    */

    int main() {
      char string1[100] = "This is a string ";
      char string2[] = "This is another string ";
      char *string3 = "third string";

      printf("String1 is \"%s\"\n", string1);

      /* Append string2 to the end of string1 */
      strcat(string1, string2);
      printf("String1 is now \"%s\"\n", string1);

      /* Append 5 chars from string3 to the end of string1 */
      strncat(string1, string3, 5);
      printf("String1 is \"%s\"\n", string1);

      return 0;
    };

    TOP

    Cloning

    Sometimes, it is necessary to clone the contents of a string, so that the copy can be manipulated without affecting the original string. Hence, it is necesssary to quickly copy a string without too much fuss. You can always copy the string using the strcmp function, but there is also another method, i.e. use the function strdup. Note that strdup allocates memory dynamically for the copy and you must free this memory using the free function, when you are done with the copy.

    STRDUP(3) Linux Programmer's Manual STRDUP(3)

    NAME

    strdup - duplicate a string

    SYNOPSIS

    #include <string.h>

    char *strdup(const char *s);

    DESCRIPTION

    The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).

    RETURN VALUE

    The strdup() function returns a pointer to the duplicated string, or NULL if insufficient memory was available.

    ERRORS

    ENOMEM Insufficient memory available to allocate duplicate string.

    CONFORMING TO

    SVID 3, BSD 4.3

    SAMPLE CODE

    #include <stdio.h>
    #include <string.h>

    /*
    * strdup demo
    * Author:      Mayukh Bose
    * Purpose:     To demonstrate the usage of the strdup function
    * Description: The program uses strdup to clone a string and then
    *              manipulates the copy of the string.
    */

    int main() {
      char *original = "This is the original string";
      char *copy = NULL;
      char *ptr = NULL;

      /* Clone the original string */
      copy = strdup(original);

      printf("Original is \"%s\"\n", original);
      printf("Copy is \"%s\"\n", copy);
      
      /* Now manipulate the copy of the string */
      ptr = strstr(copy, "the"); /* Find the position of "the" */
      *ptr = '\0';               /* Truncate the copy at "the" */

      /* Now print out the original and copy again */
      printf("Original is \"%s\"\n", original);
      printf("Copy is \"%s\"\n", copy);

      free(copy); /* Don't forget to free copy, since strdup automatically
             mallocs the memory for you */

      return 0;  
    }

    TOP

    Other Functions

    There are some other string functions, which are not as frequently used as the ones above. You can determine the usage of these functions by reading the man pages.

  • strcspn
  • strsep
  • strspn
  • strtok
  • strxfrm

    In addition, Linux provides another function called strfry, whose purpose is to create anagrams of a string. Why this would be useful is beyond me, but it's there and so I'm mentioning it. This function is unique to Linux C Library and the GNU C Library alone.

    TOP