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

前端 未结 5 2077
遇见更好的自我
遇见更好的自我 2021-02-19 23:43

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 anot

相关标签:
5条回答
  • 2021-02-19 23:49

    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.

    0 讨论(0)
  • 2021-02-19 23:51

    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 ) );
    
    0 讨论(0)
  • 2021-02-19 23:56

    Just use std::string::substr:

    std::string str = "123456789abc";
    std::string first_eight = str.substr(0, 8);
    
    0 讨论(0)
  • 2021-02-20 00:10
    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!

    0 讨论(0)
  • 2021-02-20 00:14

    Just call resize on the string.

    0 讨论(0)
提交回复
热议问题