| | 1 | = HowTo: std::string = |
| | 2 | [[TracNav(TracNav/TOC_Development)]] |
| | 3 | |
| | 4 | == Reference == |
| | 5 | For detailed information, have a look at [http://www.cplusplus.com/reference/string/string/]. |
| | 6 | |
| | 7 | == Usage == |
| | 8 | {{{ |
| | 9 | #include <string> |
| | 10 | |
| | 11 | std::string myString = "test"; // Assign the string "test" |
| | 12 | myString += "1"; // Append "1" to "test" |
| | 13 | |
| | 14 | std::string otherString = "test2"; |
| | 15 | |
| | 16 | // Combines "test1", " and " and "test" |
| | 17 | std::string output = myString + " and " + otherString; |
| | 18 | |
| | 19 | std::cout << output << std::endl; |
| | 20 | |
| | 21 | // Output: |
| | 22 | // test1 and test2 |
| | 23 | |
| | 24 | |
| | 25 | if (myString == "test1") // This is true in our example |
| | 26 | { |
| | 27 | std::cout << "myString is test1" << std::endl; |
| | 28 | } |
| | 29 | }}} |
| | 30 | |
| | 31 | == Characters == |
| | 32 | {{{ |
| | 33 | #include <string> |
| | 34 | |
| | 35 | std::string myString = "test"; |
| | 36 | |
| | 37 | myString.size(); // Returns 4 |
| | 38 | |
| | 39 | // Iterate through all characters: |
| | 40 | for (size_t pos = 0; pos < myString.size(); ++pos) |
| | 41 | { |
| | 42 | std::cout << pos << ": " << myString[pos] << std::endl; |
| | 43 | } |
| | 44 | // Output: |
| | 45 | // 0: t |
| | 46 | // 1: e |
| | 47 | // 2: s |
| | 48 | // 3: t |
| | 49 | }}} |
| | 50 | Note: The position is of type '''size_t'''. |
| | 51 | |
| | 52 | == Substring == |
| | 53 | {{{ |
| | 54 | #include <string> |
| | 55 | |
| | 56 | std::string myString = "abcdefghij"; |
| | 57 | |
| | 58 | // Get a substring, beginning with position 3 ('d') and length 4 ("defg"): |
| | 59 | std::string otherString = myString.substr(3, 4); |
| | 60 | |
| | 61 | std::cout << otherString << std::endl; |
| | 62 | |
| | 63 | // Output: |
| | 64 | // defg |
| | 65 | }}} |
| | 66 | |
| | 67 | == const std::string& == |
| | 68 | Use constant references to pass strings to functions or to return linked instances: |
| | 69 | {{{ |
| | 70 | class MyClass |
| | 71 | { |
| | 72 | public: |
| | 73 | void setName(const std::string& name) { this->name_ = name; } |
| | 74 | const std::string& getName() const { return this->name_; } |
| | 75 | |
| | 76 | private: |
| | 77 | std::string name_; |
| | 78 | }; |
| | 79 | }}} |
| | 80 | This avoids the creation of unnecessary copies of ''name'' and ''name_''. |