所以我讓我的代碼用于分隔字串:
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")
我沒有這方面的運氣,所以任何幫助將不勝感激!
uj5u.com熱心網友回復:
<regex>如果您的編譯器支持 C 11,我建議使用庫。
#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。
我能想到的唯一缺點是正則運算式引擎可能比簡單的手寫標記器慢。
uj5u.com熱心網友回復:
我只想在您的標記器中添加一個分隔符。根據strtok() 描述,第二個引數“是包含分隔符的 C 字串。這些可能因一次呼叫而異”。
因此,為您的標記化添加一個“空格”分隔符:從您的標記中ex[i] = strtok(NULL, ": "); 修剪任何空格,并丟棄所有空標記。最后兩個不是必需的,因為您的分隔符不會成為您收集的令牌的一部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/380355.html
