【问题标题】:How can I ignore certain strings in my string centring function?如何在字符串居中功能中忽略某些字符串?
【发布时间】:2016-11-05 10:10:54
【问题描述】:

NB:直接连接到problem I had a few years ago,但我想解决第一个问题,这不是问题的一部分,所以请不要将其标记为我之前的重复问题。

我有一个string centring function,它根据给定的宽度(即 113 个字符)将给定的字符串居中:

std::string center(std::string input, int width = 113) { 
    return std::string((width - input.length()) / 2, ' ') + input;
}

我正在使用游戏 SDK 来创建游戏服务器修改,并且此游戏 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;
}

上述函数的目标是遍历字符串,将当前字符和下一个字符添加到ostringstream,并评估ostringstream

这并不完全符合我的意愿:

<16:58:57> 8I
<16:58:57> 8IIn
<16:58:57> 8IInnc
<16:58:57> 8IInncco
<16:58:57> 8IInnccoom
<16:58:57> 8IInnccoommi
<16:58:57> 8IInnccoommiin
<16:58:57> 8IInnccoommiinng
<16:58:57> 8IInnccoommiinngg 
<16:58:57> 8IInnccoommiinngg  C
<16:58:57> 8IInnccoommiinngg  CCo
<16:58:57> 8IInnccoommiinngg  CCoon
<16:58:57> 8IInnccoommiinngg  CCoonnn
<16:58:57> 8IInnccoommiinngg  CCoonnnne

(来自服务器日志的 sn-p)

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

我想我可能错过了迭代的工作原理;我错过了什么,我怎样才能让这个功能以我想要的方式工作?

【问题讨论】:

  • 我认为你可以显示每隔一个字符串,因为你不能一次迭代两个。

标签: c++ iteration string-iteration


【解决方案1】:

所以,您真正想做的是计算字符串中$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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多