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

前端 未结 5 2114
遇见更好的自我
遇见更好的自我 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-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!

提交回复
热议问题