Strings in C++
Programming
|
In C, if you ever wanted to use strings, you would need to use a null-terminated array of characters. It was ugly, unsophisticated, and very susceptible to buffer overflows. C++ and it's STL gives you a much better solution; the string class.
Making a string is easy:
#include <string>
using namespace std;
string firstName("Oleksi");
string lastName;
lastName = "Derkatch";
Simple, as you can see. Strings keep track of their own size using the length() member:
string name("Oleksi");
name.length(); //Returns 6
name = "ma";
name.length(); //Returns 2
As you can see, changing the string value is simple as well. If you need to access individual characters of the string, you can treat the string as a character array in C. That is, you can easily do something like this:
string name("Jack");
for (int i(0); i < name.length(); ++i)
{
cout << name[i] ;
}
C++ overloads the extraction operator to work with strings so you can easily use it read in information from the cin stream:
string name;
cout<<"Enter your name: ";
cin>>name;
Note that if you want to read in more than one word, you will need to use the getline function as opposed to simply using cin like that.
If you want to use C++ strings, but you need to use a C library or something and need C-style string, you can still use the string class. It offers a method called c_str(), which returns the C version of the string defined in that string object. Handy.
Using the find method, you can easily search for substrings inside of the string. This makes a lot of lexical jobs much easier.
One can use the + operator to append a string and the == operator to compare to strings. A lot of the other operators are supported.
These are just a few features of the C++ string. Clearly it is much better than character arrays and you should avoid character arrays in almost all cases when you have the option of using C++ strings. They are a lot safer to use and to be frank, C-style strings are insane.Please login to rate coding articles.
Click here to register a free account with us. |
|
Comments
|
Please login to post comments. |
|
Hmm. I know that the STL is very optimized. I think that I'm going to do some speed tests and get back to you. I think that the convenience they provide outweighs the small speed boost. Especially with the power of today's processors.
But you've inspired me to run tests. I'll get back to you on that. :)
|
|
|
 |
Oleksi Derkatch (18) Canada, Ontario |
|
Cinjection has 14 fans
become a fan |
|
 |
|
 |
|