在字符串中查找逗号,然后将与其对应的x和y值分隔开

Finding a comma in a string then separating the x and y values that correspond with it

本文关键字:分隔 查找 字符串 然后      更新时间:2023-10-16

我目前正在为我的游戏引擎构建一个小型脚本系统的解析器。现在我正试着把一行的字符串分成几个部分,这样我就可以弄清楚信息了。例如,假设我将这一行保存到一个名为gui.ss:的脚本中

150,200

这两个整数用逗号分隔,中间没有空格。我主要想做的是找出数字的位置,以便将150保存为x值坐标整数,然后保存为y值坐标整数。任何帮助都很棒,谢谢!

使用字符串流:

std::string str;
size_t commaPosition = str.find(',');
str.replace( commaPosition, 1, " " );
stringstream ss;
ss << str;
int x, y;
ss >> x >> y;
#include <cstdlib>
#include <string>
std::string raw = "150,200";
size_t i = raw.find(',');
int x = atoi(raw.substr(0, i).c_str());
int y = atoi(raw.substr(i + 1).c_str());
std::string text = "150,200";
int x = strtol(text.c_str(), NULL, 10);
std::size_t pos = text.find(',');
int y = strtol(text.c_str() + pos + 1, NULL, 10);

我目前正在为我的游戏引擎构建一个小型脚本系统的解析器。现在我正试图把一条线分成几部分,这样我就可以算出信息

除非你真的想要,否则不要重新发明轮子。至少不是从零开始。如果您正在启动您的项目,请考虑使用现有的解析器工具。

您甚至可以使用像LUA、TCL或Python这样的嵌入式软件。它将为您的用户提供语言和现有库的功能。