Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changes between Initial Version and Version 1 of code/howto/string


Ignore:
Timestamp:
Oct 9, 2008, 1:46:17 AM (16 years ago)
Author:
landauf
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • code/howto/string

    v1 v1  
     1= HowTo: std::string =
     2[[TracNav(TracNav/TOC_Development)]]
     3
     4== Reference ==
     5For detailed information, have a look at [http://www.cplusplus.com/reference/string/string/].
     6
     7== Usage ==
     8{{{
     9#include <string>
     10
     11std::string myString = "test"; // Assign the string "test"
     12myString += "1";               // Append "1" to "test"
     13
     14std::string otherString = "test2";
     15
     16// Combines "test1", " and " and "test"
     17std::string output = myString + " and " + otherString;
     18
     19std::cout << output << std::endl;
     20
     21// Output:
     22// test1 and test2
     23
     24
     25if (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
     35std::string myString = "test";
     36
     37myString.size(); // Returns 4
     38
     39// Iterate through all characters:
     40for (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}}}
     50Note: The position is of type '''size_t'''.
     51
     52== Substring ==
     53{{{
     54#include <string>
     55
     56std::string myString = "abcdefghij";
     57
     58// Get a substring, beginning with position 3 ('d') and length 4 ("defg"):
     59std::string otherString = myString.substr(3, 4);
     60
     61std::cout << otherString << std::endl;
     62
     63// Output:
     64// defg
     65}}}
     66
     67== const std::string& ==
     68Use constant references to pass strings to functions or to return linked instances:
     69{{{
     70class 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}}}
     80This avoids the creation of unnecessary copies of ''name'' and ''name_''.