Selecting only the first few characters in a string C++
Asked Answered
M

6

23

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?

Millimicron answered 4/12, 2015 at 20:41 Comment(0)
K
29

Just use std::string::substr:

std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
Kalif answered 4/12, 2015 at 20:43 Comment(4)
His question is ambiguous, and there's no way to tell which of our answers is right. It depends what the OP meant by "the string" in "delete the rest of the characters from the string".Distributive
If the first string is under 8 characters, will doing substr on it change anything about the string? But thanks for the quick answer, it worked perfectly.Millimicron
@qlear you should read documentation - substr() is a const method ie does not change object itself under any condition.Gynaecocracy
@qlear An std::out_of_range exception will be thrown. As Slava said, std::string::substr won't modify the string it is called on; it'll return a new string instead. For a way to modify the string itsself without any indirection, see DavidSchwartz's answer.Kalif
D
6

Just call resize on the string.

Distributive answered 4/12, 2015 at 20:43 Comment(0)
K
4

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 ) );
Kristinkristina answered 4/12, 2015 at 20:46 Comment(0)
T
1

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.

Tory answered 2/2, 2017 at 4:26 Comment(0)
B
0

You can use "%.xs" like below.

char str[] = "Hello";
char target[9] = "        ";

sprintf(target, "%.8s", str);

if(strlen(str) < 8)
   target[strlen(str)]=' ';

printf("%s.", target);
Bail answered 27/7, 2023 at 6:15 Comment(0)
O
-1
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!

Oxen answered 4/12, 2015 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.