Split function in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mjbauer95
    New Member
    • Jan 2009
    • 13

    Split function in C

    Here is my function to split 2 strings.
    It has no errors but the function returns an array of lots of random characters.

    Code:
    char * split(const char * original, const char * search) {
        char split[2][1024];
    
        int i = 0;
        int j = 0;
        int flag = 0;
        int r = 1;
    
        for (i = 0; i<strlen(original); i=i+1) {
            if (!original[i]) break;
    
            if (flag == 0) {
                if (original[i] == search[0]) flag = 1;
                else split[0][i] = original[i];
            } else if (flag == 1){
                if (search[r]==original[i]) r=r+1;
                else if (r >= strlen(search)) flag=2;
                else flag=0;
            } else {
                split[1][j] = original[i];
                j=j+1;
            }
        }
        return split[2];
    }
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    After splitting the string you should put \0 at the end of the string.
    Then only u get the proper string as string ends with \0.


    Raghu

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      You write to split[0] and split[1] but return split[2] (invalid location)
      ps (style) - change x=x+1 to x++;
      and don't call strlen every loop iteration

      Comment

      • mjbauer95
        New Member
        • Jan 2009
        • 13

        #4
        How do you return both split[0] and split[1]? I assumed split[2] would be the whole array.

        Comment

        • newb16
          Contributor
          • Jul 2008
          • 687

          #5
          In additional arguments, like
          Code:
          ... char* split1, char* split2) {
          ...
          strcpy(split2,split[1]);
          return;
          Assuming that caller preallocated space where split1 and split2 point.

          Comment

          Working...