- One character surrounded by single quotes
- Examples: 'A' or '?'
- Special characters and no-graphic characters
* Denoted by preceding other characters with a (backslash)
* Examples: \n (newline), \t (horizontal tab), \v (vertical tab), \b (backspace) etc.
- Sequence of characters surrounded by double quotes
- Examples: "George", "ABC", "ABC0DF" (you have already used them in cout !!)
- They are stored as a char array !!
- A null character ('\0') is also added at the end of the array
- Important: String constant "A" is different from character constant 'A'
- Declare a character array
- Store the characters of the string into the array
- Remember to append '\0' at the end of the array
char name[7]; // room for 6 characters plus '\0' name[0]='G'; name[1]='e'; name[2]='o'; name[3]='r'; name[4]='g'; name[5]='e'; name[6]='\0';
- Important: C++ assumes that all strings are null-terminated !!
- Why is '\0' important ? It specifies the end of the string !!
char name[10]; // room for 9 characters plus '\0'
char name[7]; // room for 6 characters plus '\0'name[0]='G'; name[1]='e'; name[2]='o'; name[3]='r'; name[4]='g'; name[5]='e'; name[6]='\0'; // i.e., the last character is stored at the 6th place // the other 3 places remain unutilized // thus, strings can be of variable length
int StrLength(const char str[]) { int i = 0; while(str[i] != '\0') ++i; return i; }
- Examples: cout << StrLength(name); or cout << StrLength("George"); (answer will be 6)
- Create and initialize strings
- Input a string
- Output a string
- Determine the length of a string
- Compare two strings
- Copy one string to another
- One way: char name[7] = {'G', 'e', 'o', 'r', 'g', 'e', '\0' };
- Another way: char name[7] = "George"; or char name[] = "George"; (no '\0' !! Why ??)
- Aggregate assignment is not legal !!
char name[]="George"; // this is legal ... name="John"; // this is illegal !!
- Warning: what if the character array is not large enough ?
* characters will be stored into memory locations past the end of the array
- Warning: what if the string contains blank characters ??
* cin skips all whitespace (blanks, newlines, etc.) characters !!!
* Use the cin.get() function instead !!
- Application: reading input file names during execution !!
- C++ offers a large number of functions for manipulating strings