Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
user3483203 Avatar asked Dec 04 '15 20:12

user3483203


People also ask

How do I retrieve the first 5 characters from a string?

string str = (yourStringVariable + " "). Substring(0,5). Trim();

How do you find the first few letters of a string?

To access the first n characters of a string in Java, we can use the built-in substring() method by passing 0, n as an arguments to it. 0 is the first character index (that is start position), n is the number of characters we need to get from a string. Note: The extraction starts at index 0 and ends before index 3.

How do you get the first three letters of a string?

To get the first three characters of a string, call the substring() method and pass it 0 and 3 as parameters. The substring method will return a new string containing the first three characters of the original string.

How do you get the first two characters of a string?

Use the String. substring() method to get the first two characters of a string, e.g. const first2 = str. substring(0, 2); . The substring method will return a new string containing the first two characters of the original string.


3 Answers

Just use std::string::substr:

std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
like image 159
cadaniluk Avatar answered Oct 12 '22 23:10

cadaniluk


Just call resize on the string.

like image 37
David Schwartz Avatar answered Oct 13 '22 01:10

David Schwartz


If I have understood correctly you then just write

std::string message = holder.substr( 0, 8 );

Jf you need to grab characters from a character array then you can write for example

const char *s = "Some string";

std::string message( s, std::min<size_t>( 8, std::strlen( s ) );
like image 29
Vlad from Moscow Avatar answered Oct 13 '22 01:10

Vlad from Moscow