C String

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:

    1// scan through the C string once
    2char cstr1[] = "abcde";
    3for (int i = 0; cstr1[i] != '\0'; ++i)
    4  cout << cstr1[i];
    5
    6// strlen will scan through the array once
    7// scan through the C string twice
    8for (int i = 0; i < strlen(cstr1); ++i)
    9  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

char Functions

  • cctype header (not typo, two c letters) #include <cctype>

  • isalpha

  • isdigit

  • isspace

  • islower

  • isupper

  • toupper

  • tolower