【问题标题】:Splitting string with colons and spaces?用冒号和空格分割字符串?
【发布时间】:2022-01-17 10:33:00
【问题描述】:

所以我已经让我的代码用于分隔字符串:

    String c;
 
    for (int j = 0 ; j < count; j++) {
        c += ip(ex[j]);
    }
  
    return c;                      
}

void setup() {
    Serial.begin(9600);
}

我没有运气,所以任何帮助将不胜感激!

【问题讨论】:

    标签: c++ arduino


    【解决方案1】:

    我会简单地为您的分词器添加一个分隔符。从 strtok() description 开始,第二个参数“是包含分隔符的 C 字符串。这些可能因调用而异”。

    因此,在您的标记中添加一个“空格”分隔符:ex[i] = strtok(NULL, ": "); trim any whitespace 从您的标记中,并丢弃所有空标记。最后两个应该不是必需的,因为分隔符不会成为您收集的令牌的一部分。

    【讨论】:

      【解决方案2】:

      如果你的编译器支持 C++11,我建议使用 &lt;regex&gt; 库。

      #include <fstream>
      #include <iostream>
      #include <algorithm>
      #include <iterator>
      #include <regex>
      
      const std::regex ws_re(":| +");
      void printTokens(const std::string& input)
      {
          std::copy( std::sregex_token_iterator(input.begin(), input.end(), ws_re, -1),
                     std::sregex_token_iterator(),
                     std::ostream_iterator<std::string>(std::cout, "\n"));
      }
      
      int main()
      {
          const std::string text1 = "...:---:...";
          std::cout<<"no whitespace:\n";
          printTokens(text1);
      
          std::cout<<"single whitespace:\n";
          const std::string text2 = "..:---:... ..:---:...";
          printTokens(text2);
      
          std::cout<<"multiple whitespaces:\n";
          const std::string text3 = "..:---:...   ..:---:...";
          printTokens(text3);
      }
      

      库的描述在cppreference。如果你不熟悉正则表达式,上面代码中const std::regex ws_re(":| +"); 的部分表示应该有':' 符号或(or 在由管道符号'|' 表示的正则表达式中)任意数量的空格(' +' 代表'一个或多个位于加号之前的符号')。然后可以使用这个正则表达式来标记任何带有std::sregex_token_iterator 的输入。对于比空格更复杂的情况,有很棒的regex101.com
      我能想到的唯一缺点是正则表达式引擎可能比简单的手写标记器慢。

      【讨论】:

      • 感谢您的意见,但这不适用于 arduino IDE。
      • 错误是什么?
      猜你喜欢
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 2018-03-22
      • 2020-11-18
      • 2023-03-15
      相关资源
      最近更新 更多