[英]How to split a string and store in different variables of a structure?
我有一個字符串" IN1::1209 OUT1::677 CURR1::4 KWh1::3 "
,所以我只需要將值存儲在結構中。 基本上我的意思是 ex: IN::1209
在這里我只想要1209
值並且將該值存儲在結構變量中。
在 C 中, strtok()
function 用於根據特定的分隔符將字符串拆分為一系列標記。 令牌是從原始字符串中提取的 substring。
strtok()
function 的一般語法是:
char *strtok(char *str, const char *delim)
例子:
#include<stdio.h>
#include <string.h>
int main() {
char string[50] = "Hello! We are learning about strtok";
// Extract the first token
char * token = strtok(string, " ");
// loop through the string to extract all other tokens
while( token != NULL ) {
printf( " %s\n", token ); //printing each token
token = strtok(NULL, " ");
}
return 0;
}
輸出:
Hello!
We
are
learning
about
strtok
這是一個 function 通過引用接收一個字符串,這是您要拆分的參數(在我的情況下是鍵值字符串)和另一個字符串,這是分隔符參數。
它返回std::pair
中第一個字符串參數( line
)的兩個(由delimiter
)部分。
std::pair<std::string, std::string> split_key_value_pair( const std::string & line, const std::string & delimiter ){
std::size_t pos = line.find( delimiter );
std::pair<std::string, std::string> key_value;
key_value.first = line.substr(0, pos);
key_value.second = line.substr(pos + delimiter.size());
return key_value;
}
基本上,通過 delimiter 參數分割你想要的文本后,你可以得到重要的部分, first
或second
。
例子
/*create input */
std::string my_text = "IN::1209";
std::string delimiter = "::";
/* call routine */
std::pair<std::string, std::string> key_value = split_key_value_pair(my_text, delimiter);
/* print to screen the output */
std::cout << key_value.first() << std::endl; //will print IN
std::cout << key_value.second() << std::endl; //will print 1209
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.