// str2.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // // The C-Style character string (char*) originated with the C language and continues // to be supported by C++ (see str1.h & str1.cpp for full details). In fact, until // Standard C++, it was the only string support available. // Standard C++ provided a common implementation of a string class abstraction. // // The C++ string type provides various functionality including: // - Initialization of a string with another string (not supported by the C-style string), // - Copy strings (strcpy with C-Style) // - Access individual character in a string (can be done through pointer traversal with C-Style) // - String comparisons (strcmp with C-Style) // - Appending of strings (strcat & strncat with C-Style) // - Character count in a string (strlen with C-Style) // // - Detection if a string is empty (with C-Style, this can be done through: if (!str || !*str) {….} ) // // This program illustrates some of these C++ string type operations. It should be // noted however that string implementation by the standard library actually provides // a great deal more than this functionality. // // The Standard C++ generic algorithms can also be used with the string type. // // Key Points: 1) Standard C++ string type // 2) Standard C++ generic algorithms #include #include #include using namespace std; int main() { string s1 ("Greeting from STL \n The Standard Template Library."); string s2 = "Hello ", s3 = "there.", s4; // s4 is an empty string cout << "The size (length) of s1 is: " << s1.size(); cout << "\nNotice that the \\n character is counted; the \\0 character is not. \n"; if (s4.empty()) { cout << "\ns4 is empty; will perform some string operations.\n"; s2 += s3; s4 = s2; cout << "\ns2 now is: " << s2 << "\ns3 now is: " << s3 << "\nand s4 now is: " << s4 << endl; cout << "\nModifying s2 and s4; will they affect each others? \n"; replace(s2.begin(), s2.end(), 'e', 'x'); //.replace is from the generic algorithms; replace(s4.begin(), s4.end(), 'e', 'o'); // it is not part of the string type cout << "\ns2 now is: " << s2 << "\nand s4 now is: " << s4 << endl; } cout << endl; return 0; } /* The output The size (length) of s1 is: 50 Notice that the \n character is counted; the \0 character is not. s4 is empty; will perform some string operations. s2 now is: Hello there. s3 now is: there. and s4 now is: Hello there. Modifying s2 and s4; will they affect each others? s2 now is: Hxllo thxrx. and s4 now is: Hollo thoro. */