gpt4 book ai didi

c++ - 如何忽略字符串居中函数中的某些字符串?

转载 作者:行者123 更新时间:2023-11-30 05:25:35 26 4
gpt4 key购买 nike

注意:直接连接到 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

(来自服务器日志的片段)

这里是问题的简要总结:

enter image description here

我想我可能不知道迭代是如何工作的;我错过了什么,我怎样才能让这个功能按照我想要的方式工作?

最佳答案

因此,您真正要做的是计算字符串中 $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>

关于c++ - 如何忽略字符串居中函数中的某些字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38171813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com