【问题标题】:Splitting a string with no spaces in C++在 C++ 中拆分没有空格的字符串
【发布时间】:2021-08-11 13:29:58
【问题描述】:

我有一个由键值对组成但没有分隔符的字符串:

A0X3Y21.0

所有值都可以是浮点数。如何将此字符串拆分为:

A = 0, X = 3, Y = 21.0

我目前的方法是使用 strtof() ,除了一个恼人的情况,即 0 在 X 之前,因此上面的字符串被拆分为:

A = 0x3, Y = 21.0

【问题讨论】:

    标签: c++ string split key-value


    【解决方案1】:

    假设你只需要打印这些,你甚至不必使用strtof,你只需要找到浮点字符串的开头和结尾。这是一个演示这一点的函数(此函数假定字符串中变量名的长度仅为一个字符,因为从您的示例开始,但如果需要修复它并不难):

    #include <iostream>
    #include <string>
    #include <string_view>
    
    void foo(const std::string_view str)
    {
        for (size_t i = 0; i < str.size(); ++i)
        {
            std::cout << str[i] << " = ";
            size_t float_end_pos = str.find_first_not_of("1234567890.", i + 1) - 1;
            std::string_view float_str = str.substr(i + 1, float_end_pos - i);
            std::cout << float_str << '\n';
            i = float_end_pos;
        }
    }
    
    int main()
    {
        foo("A0X3Y21.0");
    }
    

    输出:

    A = 0
    X = 3
    Y = 21.0
    

    将这个基本前提调整到你需要做的任何事情上应该不会太难。

    【讨论】:

      【解决方案2】:

      对于解析,通常我使用std::stringstreams,在标题&lt;sstream&gt; 中定义。此处使用示例:

      #include <sstream>
      #include <string>
      #include <iostream>
      
      int main() {
          std::stringstream parser("A0X3Y21.0");
          std::stringstream output;
          char letter;
          double value;
          while (parser>>letter&&parser>>value) {
              output << letter;
              output << " = ";
              output << value;
              output << " ";
          }
          std::cout<<output.str();
      }
      

      这会输出这个:

      A = 0 X = 3 Y = 21
      

      【讨论】:

      • 完美运行,谢谢!我试过了,但它只显示了整个字符串?有什么不同? while(stream) { 字符串块;流>>块; cout
      • 啊啊啊我明白了,stringstream 使用变量类型来确定如何标记字符串,这很聪明!
      • @MaxPeglar-Willis 很高兴你知道了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多