Search code examples
c++stringc-strings

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


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?


Solution

  • Just use std::string::substr:

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