In C++ there are two ways to process strings. C-Strings which are an array of characters terminated by a null character, or the C++ style string object.
The string class hides the details of how the string is stored from the user – remember one of the tasks of a class is to abstract the data from the end user. This is a perfect example of this.
There are two ways to create a string – can you guess which one is actually better?
string s1 = "This is a string.";
string s2("This is a string.");
The second version is actually more efficient. The first version creates an empty string, then assigns a value. The second assigns the value as it is created.
These are not the only two methods of course. You can pass a C-Style string to the constructor, since the constructor is overloaded, but this isn’t very common.
String Methods
We’ve seen a few string methods already – such as at()
. Let’s look at some more – many of which you can assume already existed, even if you weren’t fully aware of them.
Any good class definition will include methods that the developer thinks will be commonly needed. These may even be overloaded to make things even easier.
Appending a String
The append method is a good example of this. Each of these functions appends data to an existing string – that is adds it to the end. However, there are different ways of doing this based upon what you need, such as adding a whole string, or just part of it.
append(string s) | Appends the string s to the existing string. |
append(string s, int index, int n) | Appends n number of characters in string s, starting at the index position. |
append(string s, int n) | Appends the first n number of characters from string s. |
append(int n, char ch) | Appends n copies of the character ch to the string. |
Assigning a string is another example. Instead of adding data to the string, you replace it with the assign()
set of methods. There are five overloaded methods for this.
string s1("Welcome");
cout << s1 << endl; // prints Welcome
s1.assign("Hello");
cout << s1 << endl; // prints Hello
Inserting and Replacing Strings
You can use the insert and replace methods to insert a substring into another string, or replace a substring in a string. Note that these are different than the append method which adds a string to the end of an existing string, because it can be in the middle of your string.
string s("Welcome to my world.");
cout << s << endl; // prints Welcome to my world.
cout << s.replace(14, 5, "life") << endl; // prints Welcome to my life.
cout << s.insert(11, "my ") << endl; // Welcome to my my life.
String Sizes
There are sometimes similar methods with a class. Sometimes it is up to the developer to make these, some for good reason. In the string class, there are three seemingly similar methods – length()
, size()
, and capacity()
.
While length and size are aliases, i.e. the same, capacity()
will return a the same or larger number. This is the internal buffer size, which is used internally – as a developer we rarely need this information.
Removing Data from a String
The clear()
, erase()
, and empty()
methods seem similar, but do different things.
clear() | Clears out the string, making it store no value. |
erase(int index, int n) | Deletes part of the string, starting at the index, and for n characters. |
empty() | Returns a boolean value is the string is empty. |
Comparing Strings
Instead of using >, <, or == to check for comparing strings, instead, you use the compare method. This method is overloaded so you can compare part of a string with another string, or the whole string.
If you get a value < 0 from the method, then the first string is less than the one passed to compare(). A value of 0 (Zero) means they are the same, and greater than zero means the string is bigger than the string passed to it.
string s1("Welcome");
string s2("Hello");
cout << s1.compare(s2) << endl;
cout << s2.compare(s1) << endl;
cout << s1.compare("Welcome") << endl;
SubStrings
While you can get a single character using the at()
method, what happens if you want to get more than that single character. Well that’s where you use the substr()
method.
This method is overloaded with two types. One allows you to get the string from a certain point on. The other let’s you get a number of of characters, from a specified point.
string s("Welcome to my world.");
cout << s.substr(15) << endl; // prints out world.
cout << s.substr(12,2) << endl; // prints out my
Searching a String
The find method is used to locate a string within a string. There are four overloaded functions total – they come in pairs – one for passing in a string, the other for passing in a character. With all of them, they return the position where the string is found.
find(string s) | Returns the position at which the string s is found. |
find(string s, int index) | Returns the position at which the string s is found, but only starts looking after the index. |
find(char ch) | Returns the position at which the character ch is found. |
find(char ch, int index) | Returns the position at which the char ch is found, but only starts looking after the index. |
string s("Welcome to my world.");
cout << s.find("my") << endl; // prints 11
cout << s.find("my", 20) << endl; // prints 4294967295 - not a position
cout << s.find('w') << endl; // prints 14 - this is case sensitive,
// so 'W' doesn't count
cout << s.find('w', 10) << endl; // prints 14
String Operators
Operators are like the +, -, etc, and not methods. However, they still provide a way to interact with the string object.
[] | Works similar to the at() method allowing you to get a character at a specific index. |
= | Copies the value of one string to another. |
+ | Concatenates (joins) two strings together to form a new string. |
+= | Concatenates a string to another existing string. |
<< | Inserts a new string into a stream. |
>> | Extracts characters from a stream to a string delimited by white-space. |
<,>,==,>=,<=,!= | The six relational operators. |
String Stream
This library allows you to manipulate strings so that you don’t have to write special code. It makes working with strings similar to working with a stream, which you are used to – for example cout is an output stream, and cin is an input stream.
Converting numbers into strings
Previously we converted strings into numbers. However, you often need to do the reverse. You can do this with a stringsteam
object. Simple pass a number to it like you would a normal stream (like the cout stream) and then use it to convert.
You will need to include the sstream
library.
stringstream ss;
ss << 3.141592;
string s = ss.str();
Splitting Strings
To split a string you need to write some code which manipulations a string like a stream. By using a delimiter, you can split a string at the word break (space).
string text("Welcome to my world.");
stringstream ss(text);
cout << "The words in the text, one at a time are: " << endl;
string word;
while (!ss.eof())
{
ss >> word; // get the next word in the string and
// assign it to the word variable
cout << word << endl;
}
The String Class was originally found on Access 2 Learn