C++ 如何在字符串定心函数中忽略某些字符串?

C++ 如何在字符串定心函数中忽略某些字符串?,c++,iteration,string-iteration,C++,Iteration,String Iteration,注:直接连接到a,但我想解决第一个问题,它不是问题的一部分,所以请不要将其标记为我先前问题的重复 我有一个根据给定宽度(113个字符)将给定字符串居中的 我使用游戏SDK来创建gameserver修改,此游戏SDK支持游戏命令控制台中的彩色字符串,这些字符串使用美元符号和0-9(即,$1)数字表示,并且不在控制台中打印 上面的字符串居中函数将这些标记视为整个字符串的一部分,因此我想将这些标记占用的字符总数添加到宽度,以便字符串实际居中 我已尝试修改该函数: std::string centre(

注:直接连接到a,但我想解决第一个问题,它不是问题的一部分,所以请不要将其标记为我先前问题的重复

我有一个根据给定宽度(113个字符)将给定字符串居中的

我使用游戏SDK来创建gameserver修改,此游戏SDK支持游戏命令控制台中的彩色字符串,这些字符串使用美元符号和0-9(即,
$1
)数字表示,并且不在控制台中打印

上面的字符串居中函数将这些标记视为整个字符串的一部分,因此我想将这些标记占用的字符总数添加到宽度,以便字符串实际居中

我已尝试修改该函数:

std::string centre(std::string input, int width = 113) { 
    std::ostringstream pStream;
    for(std::string::size_type i = 0; i < input.size(); ++i) {
        if (i+1 > input.length()) break;
        pStream << input[i] << input[i+1];
        CryLogAlways(pStream.str().c_str());
        if (pStream.str() == "$1" || pStream.str() == "$2" || pStream.str() == "$3" || pStream.str() == "$4" || pStream.str() == "$5" || pStream.str() == "$6" || pStream.str() == "$7" || pStream.str() == "$8" || pStream.str() == "$9" || pStream.str() == "$0")
            width = width+2;
        pStream.clear();
    }
    return std::string((width - input.length()) / 2, ' ') + input;
}
(来自服务器日志的代码段)

以下是该问题的简要总结:


我想我可能错过了迭代是如何工作的;我遗漏了什么?我如何才能使这个函数以我希望的方式工作?

因此,您真正想要做的是计算字符串中
$N
的实例,其中
N
是一个十进制数字。为此,只需使用
std::string::find
在字符串中查找
$
的实例,然后检查下一个字符是否为数字

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
}
要使用
std::isdigit
,首先需要:

#include <cctype>
#包括

我认为可以每隔一个字符串显示一次,因为不能一次迭代两个字符串。
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
}
#include <cctype>