2013-04-13 27 views
2

我有这样的文字:如何将char *分割为C中的子字符串?

char* str="Hi all.\nMy name is Matteo.\n\nHow are you?" 

,我想通过“\ n \ n”的字符串分割到一个这样的数组:

char* array[3]; 
array[0]="Hi all.\nMy name is Matteo." 
array[1]="How are you?" 
array[2]=NULL 

我试过的strtok函数,但它不能正确分割字符串。

回答

0

基于strstr功能更通用的方法:

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 


int main(void) { 
    char* str="Hi all.\nMy name is Matteo.\n\nHow are you?\n\nThanks"; 
    char **result = NULL; 
    unsigned int index = 0; 
    unsigned int i = 0; 
    size_t size = 0; 
    char *ptr, *pstr; 
    ptr = NULL; 
    pstr = str; 

    while(pstr) { 
     ptr = strstr(pstr, "\n\n"); 
     result = realloc(result, (index + 1) * sizeof(char *)); 
     size = strlen(pstr) - ((ptr)?strlen(ptr):0); 
     result[index] = malloc(size * sizeof(char)); 
     strncpy(result[index], pstr, size); 
     index++; 
     if(ptr) { 
      pstr = ptr + 2; 
     } else { 
      pstr = NULL; 
     } 
    } ; 

    for(i = 0; i < index; i++) { 
     printf("Array[%d] : >%s<\n", i, result[i]); 
    } 
    return 0; 
} 
0

的的strtok()函数工作在一个设置单个字符定界符的。你的目标是分割两个字符的分隔符,所以strtok()并不适合。

你可以通过一个循环,使用,和strchr找换行,然后检查,看看是否下一个字符也换行扫描输入字符串。

+0

你可以做一个子不循环,如果你提前知道时间的指标。你如何获得文本?下面是一个例子:http://stackoverflow.com/questions/4214314/get-a-substring-of-a-char –

1
#include <stdio.h> 
#include <string.h> 

int main(){ 
    char *str="Hi all.\nMy name is Matteo.\n\nHow are you?"; 
    char *array[3]; 
    char *ptop, *pend; 
    char wk[1024];//char *wk=malloc(sizeof(char)*(strlen(str)+3)); 
    int i, size = sizeof(array)/sizeof(char*); 
/* 
array[0]="Hi all.\nMy name is Matteo." 
array[1]="How are you?" 
array[2]=NULL 
*/ 
    strcpy(wk, str); 
    strcat(wk, "\n\n"); 
    for(i=0, ptop=wk;i<size;++i){ 
     if(NULL!=(pend=strstr(ptop, "\n\n"))){ 
      *pend='\0'; 
      array[i]=strdup(ptop); 
      ptop=pend+2; 
     } else { 
      array[i]=NULL; 
      break; 
     } 
    } 
    for(i = 0;i<size;++i) 
     printf("array[%d]=\"%s\"\n", i, array[i]); 
    return 0; 
} 
+0

谢谢!这就是我要的。我得到的文本形式与该文件: '\t如果(FILEREAD) \t { \t \t FSEEK(FILEREAD,0,SEEK_END); \t \t length = ftell(fileRead); \t \t fseek(fileRead,0,SEEK_SET); \t \t buffer = malloc(length); \t \t如果(缓冲液) \t \t { \t \t \t的fread(缓冲液,1,长度,FILEREAD); \t \t} \t \t FCLOSE(FILEREAD); \t}' –