The standard library includes a string class. They are more useful and robust than C-strings (a null-terminated array of char) and contain support of localization. C++ strings have no special language hooks—they are implmented entirely in standard C++. To use the string class, you need to include the string header file like this: #include <string>
The examples here use the string class. There is another class, wstring, that is identical to string, but uses wchar_t instead of char. This provides support for unicode and certain Asian character sets.
The following example shows how to create strings and then do simple finds and manipulation.
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
//Check that the input is good
if (argc != 2)
{
std::cout << "USAGE: " << argv[0] << " <somestring>\n";
exit(1);
}
std::string s1("hello world"); //create a string from a C-string
std::string s2(argv[1]); //create a string from command line input
std::string::size_type findex; //this is an index to a string
//The type should always be size_type, not int
//or unsigned int, otherwise comparisons to npos
//may not work
findex = s2.find('Z');
if ( findex != std::string::npos ) //if the find fails, it returns npos
{
std::cout << "The string you inputted contains a 'Z' at index "
<< findex << "\n";
}
else
{
std::cout << "I'm sorry. The string you inputted contains no 'Z'\n";
}
s2.assign(s1.rbegin(), s1.rend());
s2.append("\n"); //add a newline at the end of s2
std::cout << "Here is 'hello world' backwards:\n" << s2;
std::cout << "The 4th index of s2 is:\n" << s2.at(4) << "\n"
<< "The 6th index of s2 is:\n" << s2[6] << "\n";
}
Strings support == for equality comparison and <, >, <=, >= for lexicographical comparison.
#include <iostream>
#include <string>
int main(void)
{
std::string s1("aaaaa");
std::string s2("aaaab");
std::cout << "s1: " << s1 << "\n"
<< "s2: " << s2 << "\n";
if ( s1 < s2 )
{
std::cout << "s1 is less than s2\n";
}
if (s1 == std::string("aaaaa")) //I have to make the C-string into a string
//before the comparison
{
std::cout << "s1 is equal to aaaaa\n";
}
}
The + operator concatenates strings, and += appends to them
#include <string>
int main(void)
{
std::string s1("hello");
std::string s2("world");
s1+=" " + s2; //s1 now equal to "hello world";
}
Copyright ©2006 Joel Eidsath