Indexing Strings

Contents

Indexing Strings#

Indexing#

Listing 21 string-indexing.cpp#
#include <iostream>
#include <string>

int main() {

    std::string a{"May the force be with you."};

    std::cout << a << std::endl;

    std::cout << a[0] << std::endl;
    std::cout << a[1] << std::endl;

}

Caution

You need to be aware that indexing is in terms of bytes, and if a character (like "π") requires more than a single byte, you might be get what you expect.

We can use the .size() function on a string to see how many bytes it requires.

Listing 22 size.cpp#
#include <string>
#include <iostream>

int main() {

    std::string a("π");

    std::cout << "our string requires " << a.size() << " bytes" << std::endl;
    std::cout << a[0] << std::endl;

}

For this reason, it is best to stick with the ASCII character set.