首页 > 解决方案 > 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;
}

这太模糊和复杂,根本不起作用。任何帮助,将不胜感激!

标签: c++string

解决方案


#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,因为我们之前添加了它并且我们需要距离。简单的数学逻辑。


推荐阅读