繁体   English   中英

用冒号和空格分割字符串?

[英]Splitting string with colons and spaces?

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

const char  one[2] = {'s', 'o'};
const char *two[2] = {"...", "---"};
  
char ip(String m) {
    for (int i = 0 ; i < 2 ; i++) {
        if (strcmp(m.c_str(), two[i]) == 0) {
            return one[i];
        }
    }
}

String ipRe(char d[]) {
    int count = 0;
    char *k = d;
 
    for (count = 1; k[count]; k[count] == ':' ? count++ : *k++) {}
 
    // Serial.println(count);
  
    char *ex[count] = {NULL};
    ex[0] = strtok(d, ":");
 
    int i = 0;
 
    while (i < count) { // 3
        i++;
        ex[i] = strtok(NULL, ":");
    }
 
    String c;
 
    for (int j = 0 ; j < count; j++) {
        c += ip(ex[j]);
    }
  
    return c;                      
}

void setup() {
    Serial.begin(9600);
    Serial.println(ipRe("...:---:..."));
}

应返回"sos" ,但是如果字符串有空格(或多个空格),我该如何拆分:

Serial.println(ipRe("..:---:... ..:---:..."));

所以它返回"sos sos" (当前返回"so os"

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

如果您的编译器支持 C++11,我建议使用<regex>库。

#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在由 pipe 符号“|”表示的正则表达式中)任意数量的空格(“+”代表“一个或多个位于加号之前的符号”)。 然后可以使用这个正则表达式来标记任何带有std::sregex_token_iterator的输入。 对于比空格更复杂的情况,有很棒的regex101.com
我能想到的唯一缺点是正则表达式引擎可能比简单的手写标记器慢。

我只需向您的分词器添加一个令牌。 strtok() 描述中,第二个参数“是包含分隔符的 C 字符串。这些可能因调用而异”。

因此,在您的标记化中添加一个“空格”分隔符: ex[i] = strtok(NULL, ": "); 从您的标记中修剪任何空白,并丢弃任何空标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM