【发布时间】:2022-01-13 17:40:57
【问题描述】:
所以我需要拆分给定的字符串:
const char *inputs[] = {"111adbhsd111gfhds","goal!","zhd!111oosd","111let111"};
输出:
char *outputs[]={"adbhsd","gfhds","goal!","zhd!","oosd","let"}
分隔符在哪里: "111" 。 我尝试使用 strtok ,但由于分隔符是多个字符,它不起作用!
任何想法,它如何提供输出,都会有所帮助!
到目前为止我做了什么:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
size_t split(
char **outputs, // outputs
const char *separator, // the delimiter
const char **inputs,
size_t num_inputs // no. of input strings, given in input array
){
size_t num_outputs = 0;
int l= 0;
for(size_t i = 0; i < num_inputs ; i++){
if(strstr(*(inputs+i), separator) != NULL){ // to check, if the string of the given input array has the delimiter
char* pos = strstr( *(inputs+i), separator);
//having problem in this part
}
else
{
strcpy( outputs[l] , *(inputs+i));;
l++;
num_outputs++;
}
}
return num_outputs;
}
int main(){
const char *inputs[] = {
"111abdhsd111gfhds",
"goal!",
"zhd!111oosd",
"111let111"
};
char *outputs[] ={malloc(1000),malloc(1000),malloc(1000),malloc(1000),malloc(1000),malloc(1000)};
split(outputs, "111", inputs, 4);
for(int i =0; i < 6; i++)
{
printf("The output[%d] is : %s" ,i, outputs[i]);
free(outputs[i]);
}
return 0;
}
【问题讨论】:
-
分割字符串需要找到分隔符;你做了什么来解决这部分问题?
-
@SJoNIne 我有个主意!您需要为每个提取的字符串动态分配内存。
-
查找
strstr()。 -
@AndrewHenle: Indeed.
-
事实上,是的,@FredLarson:stackoverflow.com/questions/70276920/…(需要 20K+)。发帖人将其删除,然后发布了一份新副本(尽管稍作修改)。