/* ** $Id: strings.cc 824 2008-03-09 19:23:52Z phf $ ** ** Examples of using the std::string class, should get ** you "That Java Feeling" again... :-) */ #include #include int main() { // Two ways of declaring and initializing strings, essentially // the same; we'll talk about some of this later... std::string name = "Peter Froehlich"; std::string title( " the Third" ); // A special way to make a string filled with a certain char. std::string bar( 10, '*' ); // Printing a string, no surprise here I hope? Obviously << // is overloaded for std::string as well as int, char, ... std::cout << bar << std::endl; // Aha! String concatenation, just like in Java! :-) std::cout << name + title << std::endl; // Need to the length of a string? No more strlen() crap, we // can ask the string directly (in two ways even :-)! std::cout << name.size() << std::endl; std::cout << name.length() << std::endl; // We can also get a certain character inside the string using // an overloaded [] operator. Java needs charAt() for this, we // are cooler now. :-) std::cout << name[4] << std::endl; // We can still use some of the old C-style string stuff of // course, we can even make a string out of a C-style string. char buf[] = "bla bla bla"; std::string bla(buf); std::cout << buf << std::endl; std::cout << bla << std::endl; // We can also take a std::string and turn it back into an old // C-style string, but I'd rather not show you. Always use the // std::string stuff! return 0; }