Recently I spent a whole lot of time on file compression and decompression with zlib. Thought I’d better write something about it. But before that, let me finish the review of C++ fundamentals. Today I’ll write about Strings in C++.
Two types of String are available in C++: C-Strings (C-style Strings), and STL Strings.
C-String
C-String is a fundamental type in C++. Comparing to STL String, C-String is small, simple and fast. A C-String is a special case of an array of characters terminated with a 0. This is sometimes called an null-terminated string. A C-String can be printed out with a printf
statement using the %s
format string. We can access the individual characters in a C-String just as we do in an array.
Example: print a C-String with %s
1 2 3 |
|
Example: access characters of a C-String
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Example: access characters of a C-String, using a pointer
1 2 3 4 5 6 7 8 9 10 |
|
Example: access characters of a C-String, C++ 11 style
In C++ 11, a range based loop can be used to access arrays and also C-Strings.
1 2 3 4 5 6 7 8 9 10 11 |
|
You may have noticed that the null
character in the end of the C-String was printed out in the above code snippet. This is because the range based for loop in C++ 11 looks at the entire array and doesn’t treat the null
as the end of the C-String. To get rid of the ending null
character in a C-String, we need add a condition checker inside the range based loop.
1 2 3 4 5 6 7 8 9 10 11 |
|
STL String
The STL String class is a special type of container designed to operate with sequence of characters. It’s designed with many features and available functions to operate on strings efficiently and intuitively. To use STL String, you need include string
header. The following example shows the basic usage of STL string including getting the length of a string, string concatenation, comparison, and accessing each character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|