如何使用C编程语言编写一个函数来拆分和返回带有分隔符的字符串数组?
char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
str_split(str,',');
Run Code Online (Sandbox Code Playgroud) 我有分裂字符串的问题.下面的代码有效,但只有在字符串之间是''(空格).但即使有任何空白字符,我也需要拆分字符串.是strtok()甚至是必要的?
char input[1024];
char *string[3];
int i=0;
fgets(input,1024,stdin)!='\0') //get input
{
string[0]=strtok(input," "); //parce first string
while(string[i]!=NULL) //parce others
{
printf("string [%d]=%s\n",i,string[i]);
i++;
string[i]=strtok(NULL," ");
}
Run Code Online (Sandbox Code Playgroud) 我创建了一个.ini名为configuration.ini. 该文件如下所示:
[Application]
no_of_applications= 4;
[states]
title = "Config File States available";
name = 'Active, Deactivated, Hot';
[reaction]
reac_type = ["switch_schedule", "activate_app", "disable_app";
Run Code Online (Sandbox Code Playgroud)
现在我打算从我的 C 程序中读取这个 .ini 文件。我已经#include <configuration.ini>在我的 C 程序中包含了这一行。我只想阅读 C 程序中“状态”部分的标题,即
#include<stdio.h>
#include<configuration.ini>
int main()
{
//read the variable 'title' from 'states' and print it
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我我该怎么做?
我试图将逗号分隔的字符串转换为const char*的向量.使用以下代码,按预期输出为
ABC_
DEF
HIJ
Run Code Online (Sandbox Code Playgroud)
但我明白了
HIJ
DEF
HIJ
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
码:
#include <iostream>
#include <boost/tokenizer.hpp>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s("ABC_,DEF,HIJ");
typedef boost::char_separator<char> char_separator;
typedef boost::tokenizer<char_separator> tokenizer;
char_separator comma(",");
tokenizer token(s, comma);
tokenizer::iterator it;
vector<const char*> cStrings;
for(it = token.begin(); it != token.end(); it++)
{
//cout << (*it).c_str() << endl;
cStrings.push_back((*it).c_str());
}
std::vector<const char*>::iterator iv;
for(iv = cStrings.begin(); iv != cStrings.end(); iv++)
{
cout << *iv << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:解决方案帮助下面的答案:( …
strtokfunction使用静态变量将字符串解析为标记.因此,当多次调用完成时,这会导致冲突.除了使用线程之外,我该如何执行以下操作:thx
- 我可以使用函数指针在2个不同的位置分配函数吗?这会使"strtok"中的静态变量分配到2个不同的位置吗?
//breaking up first by Sentence and than by Word.
char phrase[] = "My dog has fleas.\nAnd he gave them to me.";
char del1[] = "\n";
char del2[] = " ";
char *token1;
char *token2;
token1 = strtok( phrase, del1);
while( token1 != NULL )
{
printf("Sentence: %s",token1);
token2 = strtok( token1, del2);
while( token2 != NULL ){
token2 = strtok( NULL, del2);
printf("WORD: %s",token2);
}
token1 = strtok( NULL, del1);
}
Run Code Online (Sandbox Code Playgroud)