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?
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 ) );
Or you could use this:
#include <climits>
cin.ignore(numeric_limits<streamsize>::max(), '\n');
If the max is 8 it'll stop there. But you would have to set
const char * word = holder.c_str();
to 8. I believe that you could do that by writing
const int SIZE = 9;
char * word = holder.c_str();
Let me know if this works.
If they hit space at any point it would only read up to the space.
char* messageBefore = "12345678asdfg"
int length = strlen(messageBefore);
char* messageAfter = new char[length];
for(int index = 0; index < length; index++)
{
char beforeLetter = messageBefore[index];
// 48 is the char code for 0 and
if(beforeLetter >= 48 && beforeLetter <= 57)
{
messageAfter[index] = beforeLetter;
}
else
{
messageAfter[index] = ' ';
}
}
This will create a character array of the proper size and transfer over every numeric character (0-9) and replace non-numerics with spaces. This sounds like what you're looking for.
Given what other people have interpreted based on your question, you can easily modify the above approach to give you a resulting string that only contains the numeric portion.
Something like:
int length = strlen(messageBefore);
int numericLength = 0;
while(numericLength < length &&
messageBefore[numericLength] >= 48 &&
messageBefore[numericLength] <= 57)
{
numericLength++;
}
Then use numericLength
in the previous logic in place of length
and you'll get the first bunch of numeric characters.
Hope this helps!