我正在将一个开源游戏客户端从PC移植到Android,但是在处理NPC聊天时,有些行无法正确解析:
服务器原文:
formatted_text_ = "Now...ask me any questions you may have on traveling!!\r\n#L0##bHow do I move?#l\r\n#L1#How do I take down the monsters?#l\r\n#L2#How can I pick up an item?#l\r\n#L3#What happens when I die?#l\r\n#L4#When can I choose a job?#l\r\n#L5#Tell me more about this island!#l\r\n#L6#What should I do to become a Warrior?#l\r\n#L7#What should I do to become a Bowman?#l\r\n#L8#What should I do to become a Magician?#l\r\n#L9#What should I do to become a Thief?#l\r\n#L10#How do I raise the character stats? (S)#l\r\n#L11#How do I check the items that I just picked up?#l\r\n#L12#How do I put on an item?#l\r\n#L13#How do I check out the items that I'm wearing?#l\r\n#L14#What are skills? (K)#l\r\n#L15#How do I get to Victoria Island?#l\r\n#L16#What are mesos?#l#k"
第二行“我如何移动”不是作为新行开始,其他行以 通过换行来正常解析。
如何 和 已处理:
switch (text[first]) {
case '\\':
if (first + 1 < last) {
switch (text[first + 1]) {
case 'n':
linebreak = true;
break;
case 'r':
linebreak = ax_ > 0;
break;
}
skip++;
}
skip++;
break;
当换行为真或长度超过最大宽度时,应添加新行:
bool newword = skip > 0;
bool newline = linebreak || ax_ + wordwidth > max_width_;
if (newword || newline) {
add_word(prev, first, last_font, last_color);
}
if (newline) {
add_line();
endy_ = ay_;
ax_ = 0;
ay_ += font_.linespace();
if (!lines_.empty()) {
ay_ -= line_adj_;
}
}
那些
\r\n
序列是两个字节。 \r
是回车。 \n
是换行符。 Windows 更喜欢用 \r\n
作为行尾。 Unix 和其他地方(包括 Android)更喜欢用 \n
作为行尾。
最简单的方法就是将
\r
、\n
和 \r\n
视为有效的行尾标记。所以让我们规范化你的格式化字符串,这样
是事实上的行尾标记:
std::string s = formatted_text_;
std::string t;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '\r') {
t += '\n';
if ((i + 1 < s.size()) && (s[i + 1] == '\n')) {
i++;
}
}
else {
t += s[i];
}
}
其结果是
t
现在是以下形式的字符串:
"Now...ask me any questions you may have on traveling!!\n#L0##bHow do I move?#l\n#L1#How do I take down the monsters?#l\n#L2#How can I pick up an item?#l\n#L3#What happens when I die?#l\n#L4#When can I choose a job?#l\n..."
由于我们现在有一个分隔符来指示行尾,因此我们可以使用
getline
解析为行列表。
std::istringstream iss(t);
std::string line;
while (std::getline(iss, line, '\n')) {
lines.push_back(line);
}
lines
是一个字符串数组(向量),如下所示:
#L0##bHow do I move?#l
#L1#How do I take down the monsters?#l
#L2#How can I pick up an item?#l
#L3#What happens when I die?#l
#L4#When can I choose a job?#l
#L5#Tell me more about this island!#l
#L6#What should I do to become a Warrior?#l
#L7#What should I do to become a Bowman?#l
#L8#What should I do to become a Magician?#l
#L9#What should I do to become a Thief?#l
#L10#How do I raise the character stats? (S)#l
#L11#How do I check the items that I just picked up?#l
#L12#How do I put on an item?#l
#L13#How do I check out the items that I'm wearing?#l
#L14#What are skills? (K)#l
#L15#How do I get to Victoria Island?#l
#L16#What are mesos?#l#k
例如
line[2]
等于 #L2#How can I pick up an item?#l
。您的游戏的 #L2
和 #l
格式说明符 - 我将把它作为练习留给您。
注意:
#include <string> #include <vector> and #include <sstream>
以上代码才能工作。