[英]Extract lines containing a string from a file into another file without using strstr
[英]C: Take parts from a string without a delimiter (using strstr)
我有一個字符串,例如: "Error_*_code_break_*_505_*_7.8"
我需要使用strstr
函數通過分隔符"_*_"
用循環分割字符串並將所有部分輸入到一個新數組中,我們稱之為 -
char *elements[4] = {"Error", "code_break", "505", "7.8"}
但是strstr
只給了我一個指向字符的指針,有什么幫助嗎?
注意:第二個字符串"code_break"
仍應包含"_"
,或在任何其他情況下。
這會讓你成功一半。 該程序將字符串的分割部分打印到標准輸出; 它不會創建一個數組,但也許您可以自己添加它。
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void split(const char * str, const char * delimiter)
{
char * writable_str = strdup(str);
if (writable_str == NULL) { return; }
char * remaining = writable_str;
while (1)
{
char * ending = strstr(remaining, delimiter);
if (ending != NULL) { *ending = 0; }
printf("%s\n", remaining);
if (ending == NULL) { break; }
remaining = ending + strlen(delimiter);
}
free(writable_str);
}
int main(void) {
const char * str = "Error_*_code_break_*_505_*_7.8";
const char * delimiter = "_*_";
split(str, delimiter);
return 0;
}
這是一個將字符串拆分為數組的函數。 您必須傳遞數組的大小,以便函數不會過度填充它。 它返回它放入數組的東西的數量。 它放入數組的是指向傳遞的字符串的指針。 它通過插入空字符來結束片段來修改字符串 - 就像 strtok 一樣。
#include<string.h>
#include<stdio.h>
int split(char *string, char *delimiter, char* array[], int size)
{
int count=0;
char *current=string;
char *next;
while(current && *current!='\0')
{
next=strstr(current,delimiter);
if(!next)break;
*next='\0';
if(count<size) array[count++]=current;
current=next+strlen(delimiter);
}
if(count<size) array[count++]=current;
return count;
}
int main()
{
char string[100]="Error_*_code_break_*_505_*_7.8";
char *array[10];
int size=split(string,"_*_",array,10);
for(int i=0;i<size;i++) puts(array[i]);
return size;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.