strings/string-ex-cpp11.cc - Same - with C++ initializations. | Lecture 3 - slide 12 : 27 Program 7 |
// Same as above - but with C++ string initialization. #include <iostream> #include <string> #include <cstdlib> using std::string; using std::cout; using std::endl; int main(){ // C++11 CONSTRUCTION: string s0{}, // the empty string s1{"A string"}, s2{"Another string"}, s3{s1}, // copy constructor s4{s1,2,6}; // copy constructor, selected part // 6 characters from s: "string" cout << s4 << endl; // "string" // ELEMENT ACCESS: cout << "s1[0] = " << s1[0] << endl; // A cout << "s1[10] = " << s1[10] << endl; // Index out of range. Risky at run time! cout << "s1[0] = " << s1.at(0) << endl; // A //cout << "s1[10] = " << s1.at(10) << endl; // Compiles. Run time error : out of range. // ASSIGNMENT: s0 = s2; // Assignment - copies all chars in s2. cout << s0 << endl; // "another string" // CONVERSION TO C-STYLE STRINGS: s1 = "1234"; const char *str1 = s1.c_str(); // C++ string -> C string int str1_int = std::atoi(str1); // C-style function: atoi applied //int s1_int = std::atoi(s1); // Not possible to call atoi on a C++ string: // Cannot convert string to const char* cout << "char*: " << str1 // char*: 1234 << " int: " << str1_int << endl; // int: 1234 // COMPARISON: cout << "compare abc and def: " << string("abc").compare("def") // -1 << endl; bool b = string("abc") < string("def"); // Comparison with the operator < is cout << "b: " << b << endl; // also possible! b: 1 s1 = s2; cout << "compare s1 and s2: " // s2 has just been copied to s1 - thus equal. << s1.compare(s2) << endl; // 0 // INSERT AND APPEND: string s5 = "Poul", s6 = "Hansen"; s5 += ' '; s5 += s6; cout << "Appended names: " << s5 << endl; // Poul Hansen s5.insert(5, "Ib "); // Insert "Ib" as middle name. cout << "Insert Ib middle name: " << s5 // Poul Ib Hansen << endl; s5 = "Peter", s6 = "Andersen"; cout << s5 + " " + s6 << endl; // Concatenation: // Peter Andersen }