Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Version 1 (modified by landauf, 16 years ago) (diff)

HowTo: std::string

TracNav(TracNav/TOC_Development)?

Reference

For detailed information, have a look at http://www.cplusplus.com/reference/string/string/.

Usage

#include <string>

std::string myString = "test"; // Assign the string "test"
myString += "1";               // Append "1" to "test"

std::string otherString = "test2";

// Combines "test1", " and " and "test"
std::string output = myString + " and " + otherString;

std::cout << output << std::endl;

// Output:
// test1 and test2


if (myString == "test1") // This is true in our example
{
    std::cout << "myString is test1" << std::endl;
}

Characters

#include <string>

std::string myString = "test";

myString.size(); // Returns 4

// Iterate through all characters:
for (size_t pos = 0; pos < myString.size(); ++pos)
{
    std::cout << pos << ": " << myString[pos] << std::endl;
}
// Output:
// 0: t
// 1: e
// 2: s
// 3: t

Note: The position is of type size_t.

Substring

#include <string>

std::string myString = "abcdefghij";

// Get a substring, beginning with position 3 ('d') and length 4 ("defg"):
std::string otherString = myString.substr(3, 4);

std::cout << otherString << std::endl;

// Output:
// defg

const std::string&

Use constant references to pass strings to functions or to return linked instances:

class MyClass
{
    public:
        void setName(const std::string& name) { this->name_ = name; }
        const std::string& getName() const { return this->name_; }

    private:
        std::string name_;
};

This avoids the creation of unnecessary copies of name and name_.