How can I ignore certain strings in my string centring function?

前端 未结 1 518
梦毁少年i
梦毁少年i 2021-01-23 07:27

N.B: Directly connected to a problem I had a few years ago, but I\'d like to resolve the first issue there which wasn\'t otherwise part of the question, so please don\'t fla

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-23 08:23

    So, what you are really trying to do is count the instances of $N in your string, where N is a decimal digit. To do this, just look in the string for instances of $ using std::string::find, and then check the next character to see if it is a digit.

    std::string::size_type pos = 0;
    while ((pos = input.find('$', pos)) != std::string::npos) {
        if (pos + 1 == input.size()) {
            break;  //  The last character of the string is a '$'
        }
        if (std::isdigit(input[pos + 1])) {
            width += 2;
        }
        ++pos;  //  Start next search from the next char
    }
    

    In order to use std::isdigit, you need to first:

    #include 
    

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