c++ - C ++从字符串中的每个轴获取子字符串
问题描述
如何从字符串上的每个轴获取值?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "X:-600.913 Y:100.54 Z:412.22";
//do stuff
string X; // must be -600.913
string Y; // must be 100.54
string Z; // must be 412.22
//print individual values
std::cout << X;
std::cout << Y;
std::cout << Z;
}
我之前的尝试是
int main()
{
string text = "X:-600.913 Y:100.54 Z:412.22";
cin >> text;
int Xsecond = text.find(" Y:");
string X = text.substr(2, Xsecond - 4);
int Yfirst = text.find("Y:");
int Ysecond = text.find(" Z:");
string Y = text.substr(Yfirst + 1, Ysecond-Yfirst - 1);
cout << X;
}
这太模糊和复杂,根本不起作用。任何帮助,将不胜感激!
解决方案
#include <iostream>
#include <string>
int main()
{
std::string text="X:-600.913 Y:100.54 Z:412.22";
size_t colon=text.find(":");
size_t space=text.find(" ");
std::string X=text.substr(colon+1,space-colon-1);
colon=text.find(":",colon+1);
space=text.find(" ",space+1);
std::string Y=text.substr(colon+1,space-colon-1);
colon=text.find(":",colon+1);
space=text.find(" ",space+1);
std::string Z=text.substr(colon+1,space-colon-1);
std::cout<<X<<std::endl<<Y<<std::endl<<Z;
}
在第一个之后find
,连续的调用开始从上一个命中开始搜索。我们每次都减去 1,因为我们之前添加了它并且我们需要距离。简单的数学逻辑。
推荐阅读
- vim - Nvim 显示 Vim :h 页面
- python - imaplib 不适用于某些 Outlook365 帐户
- matplotlib - Matplotlib.Pyplot 不会改变散点图的颜色
- c++ - 在OpenGL中将SRGB纹理转换为线性
- android - Windows 10 PC 可以充当 iBeacon 吗?
- javascript - 使用 MST 的 React Navigation 5 身份验证流程,而不是“切换”
- sql - 分组数据 SQL 的运行总计
- python - ImportError:DLL 加载失败:在不同的机器上找不到指定的模块(pyinstaller)
- ios - 使用 XIB 创建自定义视图时出错
- c# - 获取ECC加密证书的字节数组