Learning materials

C String

On this page

A data structure inherited from C language to handle variable-length text.

This data structure is outdated. It is hard and insecure to use. The C++ string type is preferred.

  • A partially filed char array with a ‘\0’ (null) char to mark the end
  • not a class type. no methods!
  • [] syntax
    • no out-of-range check

Example

  • char str1[100] = "abc"

    • The C string can hold up to 99 characters (not 100)
    • The string length is 3 (not include the tailing ‘\0’)
    • The occupied spaces is 4 (include the tailing ‘\0’)
  • char str1[] = "abc"

    • The string length is 3
    • The array length is 4 (include the tailing ‘\0’)
    • The array is filled
  • loop through a C string:

    // scan through the C string once
    char cstr1[] = "abcde";
    for (int i = 0; cstr1[i] != '\0'; ++i)
      cout << cstr1[i];
    
    // strlen will scan through the array once
    // scan through the C string twice
    for (int i = 0; i < strlen(cstr1); ++i)
      cout << cstr1[i];
    
  • dynamic C string:

    char *dyn_str1 = new char[100];
    strcpy(dyn_str1, "abc");
    delete [] dyn_str1;
    

Pitfalls

  • cout << myString.size(); C string has no method at all
  • char str1[10] = {0}; cout << str1[10]; out-of-range access
  • char str2[3] = "abc"; overflows, the str2 can have at most two chars
  • c-string header #include <cstring>
  • strcpy copy
  • strncpy copy with cut off
  • strcat concatenate
  • strncat concatenate with cut off
  • strchar search a char in a C string
  • strlen get length
  • strcmp compare two C strings

char Functions

  • cctype header (not typo, two c letters) #include <cctype>
  • isalpha
  • isdigit
  • isspace
  • islower
  • isupper
  • toupper
  • tolower