String Example - Count the chars

int count_string (char *s) {
    int n=0;
    while (*s) { <-- while the thing pointed to by s is not 0
        n++; <-- increment counter
        s++; <-- set s to point to the next char
    }
    return n;
}

or

int count_string (char *s) {
    char *ptr = s;
    while (*ptr) {
        ptr++;
    }
    return (ptr - s);
}

Strings and the Standard Operators

  • The standard operators (=, ==, <, >, ...) generally don't do anything useful with strings
    • = copies the pointer to the string, not the string
    • ==, <, >, ... compares the pointer to the string, not the content of the string
  • Standard library <string.h> provides string manipulation functions
#include <string.h>
size_t strlen (const char *s); 

String Functions

  • size_t strlen (const char *s);
    • The number of characters in s preceding the null character
  • char * strcopy (char * dest, const char * src);
    • Copy characters up to and including the null character from src to dest
  • char * strcat (char * dest, const char * src);
    • Appends a copy of src to the end of dest. The initial char of src will overwrite the null char originally at the end of dest.
  • int strcomp(const char * s1, const char * s2);
    • Compares the two strings s1 and s2. Returns a value:
      • < 0 if s1 < s2
      • 0 if s1 == s2
      • > 0 if s1 > s2
  • char * strchr (const char * s, int c);
    • Find the first occurrence of c in the string s. Null pointer is returned if c is not found.
  • char *strstr (const char * s1, const char * s2);
    • Find the first occurrence of the string s2 in the string s1. Null pointer is returned if s2 is not found.