2

I have a text like this:

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

and I want to split the string by "\n\n" in to an array like this:

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

I've tried the strtok function but it does not split the string correctly.

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
Matteo Gaggiano
  • 1,254
  • 15
  • 28

3 Answers3

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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • Thanks! This is what I want. I'm get the text form a file with this: ` if (fileRead) { fseek (fileRead, 0, SEEK_END); length = ftell (fileRead); fseek (fileRead, 0, SEEK_SET); buffer = malloc (length); if (buffer) { fread (buffer, 1, length, fileRead); } fclose (fileRead); }` – Matteo Gaggiano Apr 14 '13 at 18:10
0

The strtok() function works on a set of single character delimiters. Your goal is to split by a two character delimiter, so strtok() isn't a good fit.

You could scan your input string via a loop that used strchr to find newlines and then checked to see if the next char was also a newline.

Mike Mondy
  • 76
  • 2
  • You can do a substring without the looping if you know the indices ahead of time. How are you getting the text? Here's an example: http://stackoverflow.com/questions/4214314/get-a-substring-of-a-char – Miles Alden Apr 13 '13 at 17:47
0

A more generic method based on strstr function:

#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;
}
Bechir
  • 987
  • 10
  • 26