Home | Projects | Notes > C++ Programming > Characters & Strings
Character functions (#include <cctype>)
C-style strings
Working with C-style strings
C++ strings (Should be using these in modern C++)
C++ strings are objects and used in OOPs.
Working with C++ strings
The <cctype> library includes very simple and very useful functions that allow
xxxxxxxxxx31
3function_name(char)Testing of characters for various properties (Returns true or false)
xxxxxxxxxx91isalpha(c)          True if c is a letter2isalnum(c)          True if c is a letter or digit3isdigit(c)          True if c is a digit4islower(c)          True if c is lowercase letter5isprint(c)          True if c is a printable character 6ispunct(c)          True if c is a punctuation character 7isupper(c)          True if c is an uppercase letter 8isupper(c)          True if c is an uppercase letter 9isspace(c)          True if c is whitespace Conversion of characters (Returns the converted characters)
xxxxxxxxxx21tolower(c)          Returns lowercase of c2toupper(c)          Returns uppercase of c
Sequence of characters (String variable)
Contiguous in memory
Implemented as an array of characters
Terminated by a null character (\0; character with a value of 0)
Referred to as null (or zero) terminated strings
String literal
Sequence of characters in double quotes (e.g., "Jack")
Constant
Terminated with a null character (\0)
Even though a null character is not provided to the end of the string literal, C++ inserts one for us.
Declaration and initialization
xxxxxxxxxx21char my_name[] {"Jack"};    // Jack\0 (C++ compiler will allocate 5 char for this array)2char my_name[10] {};        // Null initialized stringxxxxxxxxxx21char my_name[] {"Jack"};2my_name[4] = 'y'; // ProblemYou won't be able to do to add a
yto make itJackybecause the string size is fixed and adding ayto the end will not make the string end with a null character. But, the following is okay.xxxxxxxxxx21char my_name[8] {"Jack"}; // Jack\0\0\0\02my_name[4] = 'y'; // OK (Still null terminated)xxxxxxxxxx31char my_name[8]; // Uninitialized string (Contains garbage)2my_name = "Jack"; // Error (Both 'my_name' and '"Jack"' evaluates to an address)3strcpy(my_name, "Jack"); // OK
<cstring> library contains many functions that work with C-style strings
Copying
Concatenation
Comparison
Searching
and many more
Examples:
xxxxxxxxxx71
3char str[80];4strcpy(str, "Hello ");  // Copy5strcat(str, "there");   // Concatenate6cout << strlen(str);    // 117strcmp(str, "Another"); // > 0<cstdlib> library contains general purpose functions including functions to convert C-style strings to integer, float, long, etc.
std::string)std::string is a class in the Standard Template Library (STL) which provides a rich set of methods or functions that allows to manipulate strings easily.
#include <string>
In the std namespace
Contiguous in memory
Dynamic size
Work with input and output streams
Lots of useful member functions
Operators such as +, =, <, <=, >, >=, +=, ==, !=, [], ...
Can be easily converted to C-style string if needed
Even though C++ strings are preferred in most cases, sometimes you need to use C-style strings (e.g., interfacing with a library that's been optimized for C-style strings). In this case, you can still use C++ strings and take advantage of them, and when you need to, you can easily convert the C++ string into a C-style string and back again.
Safer (Provides bounce check and allows to find errors in the code so they can be fixed before they go into production)
Declaration and initialization (Unlike C-style strings, C++ strings are always initialized.)
xxxxxxxxxx91using namespace std;3
4string s1;              // Empty (Initialized to an empty string; Does not contain garbage)5string s2 {"Jack"};     // Jack (C-style string will be converted into a C++ string)6string s3 {s2};         // Jack7string s4 {"Jack", 3};  // Jac8string s5 {s3, 0, 2};   // Ja (Starting at index '0', 2 characters)9string s6 (3, 'x');     // xxx (Note that these are not curly braces)Assignment
xxxxxxxxxx51string s1;2s1 = "Jack";3
4string s2 {"Hello"};5s2 = s1;    // s2 will contain "Jack"Concatenation
xxxxxxxxxx71string s1 = "Hello";2string s2 = "world";3
4string s3;5
6s3 = s1 + " " + s2 + " Jack";   // Hello world Jack 7s3 = "New" + "sentence";        // Illegal ('+' only works with C++ strings!)L7: A combination of C++ strings and C-style strings is okay though!
Accessing characters using [] and at() function
xxxxxxxxxx81string s1;2string s2 {"Jack"};3
4cout << s2[0] << endl;      // J5cout << s2.at(0) << endl;   // J6
7s2[0] = 'j';    // s2 will contain "jack"8s2.at(0) = 'p'; // s2 will contain "pack"
[]does not provide bounce check, whereasat()does.
xxxxxxxxxx51// Reading characters2
3string s1 {"Jack"};4for (char c : s1)5    cout << c << " ";xxxxxxxxxx11J a c kxxxxxxxxxx51// Reading characters as integer values2
3string s1 {"Jack"};4for (int c : s1)5    cout << c << " ";xxxxxxxxxx1174 97 99 107 0  // Last character being the ascii value for '\0'Comparison (==, !=, >, >=, <, <=)
The objects are compared character-by-character lexically.
Can compare:
Two std::string objects
std::string object and C-style string literal
std::string object and C-style string variable
Examples:
xxxxxxxxxx131string s1 {"Apple"};2string s2 {"Banana"};3string s3 {"Kiwi"};4string s4 {"apple"};5string s5 {s1};     // Apple6
7s1 == s5        // True8s1 == s2        // False9s1 != s2        // True10s1 < s2         // True11s2 > s1         // True12s4 < s5         // False13s1 == "Apple"   // True (Here "Apple" is a C-style literal)Substrings (substr())
Extracts a substring from std::string.
xxxxxxxxxx11object.substr(start_index, length)Examples:
xxxxxxxxxx51string s1 {"This is test"};2
3cout << s1.substr(0, 4);    // This4cout << s1.substr(5, 2);    // is5cout << s1.substr(10, 4);   // testSearch (find())
Returns the index of a substring in a std::string.
xxxxxxxxxx11object.find(search_string)Check out
rfind()which performs the search backwards as well!
Examples:
xxxxxxxxxx81string s1 {"This is a test"};2
3cout << s1.find("This");    // 04cout << s1.find("is");      // 25cout << s1.find("test");    // 106cout << s1.find('e');       // 117cout << s1.find("is", 4);   // 58cout << s1.find("xx");      // string::npos (no position information available)L8: Can check for
string::nposin an if statement. If true, the string you are searching for wasn't there.
Removing characters (erase() and clear())
Removes a substring of a character from a std::string.
xxxxxxxxxx11object.erase(start_index, length)Examples:
xxxxxxxxxx51string s1 {"This is a test"};2
3cout << s1.erase(0, 5);     // is a test4cout << s1.erase(5, 4);     // is a5s1.clear()                  // Empties string s1Other useful functions
xxxxxxxxxx61string s1 {"Jack"};2
3cout << s1.length() << endl;    // 4 (Returns the number of chars currently in the string obj)4
5s1 += " Lee";6cout << s1 << endl;     // Jack LeeInput >> and getline()
Reading std::string from cin.
xxxxxxxxxx21getline(input_stream, dest_string)  // Reads the entire line until '\n'2getline(input_stream, dest_string, delimiter)   // Delmiter: The char you want to stop reading at
getline()does not include the new-line character\n(or delimiter), and discards it.
Examples:
xxxxxxxxxx101string s1;2cin >> s1;              // Hello there (Only accepts up to the first space)3
4cout << s1 << endl;     // Hello5
6getline(cin, s1);       // Read entire line until \n7cout << s1 << endl;     // Hello there8
9getline(cin, s1, 'x');  // this isx10cout << s1 << endl;     // this is