Selecting only the first few characters in a string C++

user3483203 picture user3483203 · Dec 4, 2015 · Viewed 39.6k times · Source

I want to select the first 8 characters of a string using C++. Right now I create a temporary string which is 8 characters long, and fill it with the first 8 characters of another string.

However, if the other string is not 8 characters long, I am left with unwanted whitespace.

string message = "        ";

const char * word = holder.c_str();

for(int i = 0; i<message.length(); i++)
    message[i] = word[i];

If word is "123456789abc", this code works correctly and message contains "12345678".

However, if word is shorter, something like "1234", message ends up being "1234 "

How can I select either the first eight characters of a string, or the entire string if it is shorter than 8 characters?

Answer

cadaniluk picture cadaniluk · Dec 4, 2015

Just use std::string::substr:

std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);