CSE 40872 Lecture 007

Topic:Strings (C)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 14, 2009

Strings (C)

Array of char terminated by '\0' (NULL).

char  s[MAX_STRLEN];
char *sptr;

sptr = malloc(sizeof(char) * MAX_STRLEN);

Functions (Length)

strlen(const char *s):
Returns length of string NOT including '\0'.
size_t strlen(const char *s) {
    size_t i;

    for (i = 0; s[i] != 0; i++) ;

    return (i);
}

Functions (Comparison)

strcmp(const char * s1, const char *s2):
Returns negative if s1 < s2, 0 if s1 == s2, positive if s1 > s2
strcasecmp:
Same as strcmp but ignores case.
if (strcmp(s1, s2) == 0)
    printf("%s is the same as %s\n", s1, s2);

Functions (Search)

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

    for (sp = s[strlen(s) - 1]; sp != s; sp--)
        if (*sp == c)
            return (sp);

    return (NULL);
}

Functions (Copy)

strcpy(char *dst, const char *src):
Copies string src into string dst.
char *strcpy(char *dst, const char *src) {
    char *dp, *sp;

    dp = dst;
    sp = src;
    while (*sp != 0)
        *dp++ = *sp++;

    return (dst);
}

Functions (Concatenate)

strcat(char *dst, const char *src):
Concatenates string src at the end of dst.
char s[MAX_STRLEN];

strcpy(s, "Hello, ");
strcat(s, "World!");

Functions (Tokenize)

strtok(char *s, const char *delim):
Parses a string into tokens delimited by characters in delim. Tokens will not contain delimiters.
char *s = "words separated by spaces.";
char *d = " ";
char *sp;

sp = strtok(s, d);
while (sp) {
    puts(sp);
    sp = strtok(NULL, d);
}

Tips

#include <string.h> // C
#include <cstring>  // C++