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
xxxxxxxxxx
31
2
3function_name(char)
Testing of characters for various properties (Returns true
or false
)
xxxxxxxxxx
91isalpha(c) True if c is a letter
2isalnum(c) True if c is a letter or digit
3isdigit(c) True if c is a digit
4islower(c) True if c is lowercase letter
5isprint(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)
xxxxxxxxxx
21tolower(c) Returns lowercase of c
2toupper(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
xxxxxxxxxx
21char my_name[] {"Jack"}; // Jack\0 (C++ compiler will allocate 5 char for this array)
2char my_name[10] {}; // Null initialized string
xxxxxxxxxx
21char my_name[] {"Jack"};
2my_name[4] = 'y'; // Problem
You won't be able to do to add a
y
to make itJacky
because the string size is fixed and adding ay
to the end will not make the string end with a null character. But, the following is okay.xxxxxxxxxx
21char my_name[8] {"Jack"}; // Jack\0\0\0\0
2my_name[4] = 'y'; // OK (Still null terminated)
xxxxxxxxxx
31char 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:
xxxxxxxxxx
71
2
3char str[80];
4strcpy(str, "Hello "); // Copy
5strcat(str, "there"); // Concatenate
6cout << strlen(str); // 11
7strcmp(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.)
xxxxxxxxxx
91
2using 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}; // Jack
7string s4 {"Jack", 3}; // Jac
8string s5 {s3, 0, 2}; // Ja (Starting at index '0', 2 characters)
9string s6 (3, 'x'); // xxx (Note that these are not curly braces)
Assignment
xxxxxxxxxx
51string s1;
2s1 = "Jack";
3
4string s2 {"Hello"};
5s2 = s1; // s2 will contain "Jack"
Concatenation
xxxxxxxxxx
71string 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
xxxxxxxxxx
81string s1;
2string s2 {"Jack"};
3
4cout << s2[0] << endl; // J
5cout << s2.at(0) << endl; // J
6
7s2[0] = 'j'; // s2 will contain "jack"
8s2.at(0) = 'p'; // s2 will contain "pack"
[]
does not provide bounce check, whereasat()
does.
xxxxxxxxxx
51// Reading characters
2
3string s1 {"Jack"};
4for (char c : s1)
5 cout << c << " ";
xxxxxxxxxx
11J a c k
xxxxxxxxxx
51// Reading characters as integer values
2
3string s1 {"Jack"};
4for (int c : s1)
5 cout << c << " ";
xxxxxxxxxx
1174 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:
xxxxxxxxxx
131string s1 {"Apple"};
2string s2 {"Banana"};
3string s3 {"Kiwi"};
4string s4 {"apple"};
5string s5 {s1}; // Apple
6
7s1 == s5 // True
8s1 == s2 // False
9s1 != s2 // True
10s1 < s2 // True
11s2 > s1 // True
12s4 < s5 // False
13s1 == "Apple" // True (Here "Apple" is a C-style literal)
Substrings (substr()
)
Extracts a substring from std::string
.
xxxxxxxxxx
11object.substr(start_index, length)
Examples:
xxxxxxxxxx
51string s1 {"This is test"};
2
3cout << s1.substr(0, 4); // This
4cout << s1.substr(5, 2); // is
5cout << s1.substr(10, 4); // test
Search (find()
)
Returns the index of a substring in a std::string
.
xxxxxxxxxx
11object.find(search_string)
Check out
rfind()
which performs the search backwards as well!
Examples:
xxxxxxxxxx
81string s1 {"This is a test"};
2
3cout << s1.find("This"); // 0
4cout << s1.find("is"); // 2
5cout << s1.find("test"); // 10
6cout << s1.find('e'); // 11
7cout << s1.find("is", 4); // 5
8cout << s1.find("xx"); // string::npos (no position information available)
L8: Can check for
string::npos
in 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
.
xxxxxxxxxx
11object.erase(start_index, length)
Examples:
xxxxxxxxxx
51string s1 {"This is a test"};
2
3cout << s1.erase(0, 5); // is a test
4cout << s1.erase(5, 4); // is a
5s1.clear() // Empties string s1
Other useful functions
xxxxxxxxxx
61string 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 Lee
Input >>
and getline()
Reading std::string
from cin
.
xxxxxxxxxx
21getline(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:
xxxxxxxxxx
101string s1;
2cin >> s1; // Hello there (Only accepts up to the first space)
3
4cout << s1 << endl; // Hello
5
6getline(cin, s1); // Read entire line until \n
7cout << s1 << endl; // Hello there
8
9getline(cin, s1, 'x'); // this isx
10cout << s1 << endl; // this is