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?
string str = (yourStringVariable + " "). Substring(0,5). Trim();
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.
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.
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.
Just use std::string::substr
:
std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
Just call resize on the string.
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With