Strings in C++ programming



Definition of Strings

The standard library provides a string type to complement the string literals. The string type provides a variety of useful string operations, such as concatenation.

For example:


    string compose(const string& name, const string& domain)
    {
    return name + # + domain;
    }
    auto addr = compose("amg","infoweb14.com");

Here, addr is initialized to the character sequence amg@infoweb14.com. ‘‘Addition’’ of strings means concatenation. You can concatenate a string, a string literal, a C-style string, or a character to a string. The standard string has a move constructor so returning even long strings by value is efficient.

The string class also has several member functions. For example, the size function returns the length of the string. It is demonstrated in the for loop in program below.

This program demonstrates some C++ string class member functions.


    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
    string str1, str2, str3;
    str1 = "ABC";
    str2 = "DEF";
    str3 = str1 + str2;
    
    // Use the size() string member function
    // and the overloaded string operator [ ].
    for (int k = 0; k < str3.size(); k++)
    cout << str3[k];
    // Use the overloaded string operator <.
    if (str1 < str2)
    cout << str1 << " is less than " << str2 << endl;
    else
    cout << str1 << " i cout << endl;
    s not less than " << str2 << endl;
    return 0;
    }

    Program Output :
    ABCDEF
    ABC is less than DEF

The table following lists many of the string class member functions and their overloaded variations.

Member Function Example Description
theString.append(str); Appends str to theString. str can be a string object or character array.
theString.assign(str); Assigns str to theString. The parameter str can be a string object or a C-string.
theString.at(x); Returns the character at position x in the string.
theString.begin(); Returns an iterator pointing to the first character in the string.
theString.capacity(); Returns the size of the storage allocated for the string.
theString.clear(); Clears the string by deleting all the characters stored in it.
theString.compare(str); Performs a comparison like the strcmp function with the same return values. str can be a string object or acharacter array.
theString.copy(str, x, n); Copies the character array str to theString, beginning at position x, for n characters. If theString is too small, the function will copy as many characters as possible.
theString.data(); Returns a character array containing a null terminated string, as stored in theString.
theString.c_str(): Returns the C-string value of the string object.
theString.empty(); Returns true if theString is empty.
theString.end(); Returns an iterator pointing to the last character of the string in theString.

PROMOTIONS