【发布时间】: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