代码之家  ›  专栏  ›  技术社区  ›  Kevin Ng

拆分字符串并存储到堆算法问题

c
  •  0
  • Kevin Ng  · 技术社区  · 6 年前

    我写的下面的代码。我在想,如果我想分割字符串但仍然保留原始字符串,这是最好的方法吗?

    调用者应该提供**字符还是函数“split”进行一个额外的malloc调用,内存管理**字符?

    另外,我想知道这是否是最优化的方法,或者我可以优化代码比这更好吗?

    我还没有调试代码,我有点不确定是调用方管理**char还是函数管理指针**char。

    #include<stdio.h>
    #include<stdlib.h>
    
    int split(char * string, char splitChar, char ** parts, int maxParts){   
        int size = 100;
        int partSize = 0;
        int len = 0;
        int newPart = 1;
        char * tempMem;
    
        /*
         * We just reverse a long page of memory
         * At reaching the space character that is the boundary of the new
         */
    
        char * mem = (char*) malloc( sizeof(char) * size );
        if ( mem == NULL ) return 0;
    
    
        for ( int i = 0; string[i] != 0; i++ ) {
          // If it is a split char we at a new part
          if ( string[i] == splitChar) {
            // If the last character was not the split character
            // Then mem[len] = 0 and increase the len by 1.
            if (newPart == 0) mem[len++] = 0;
            newPart = 1;
            continue;  
          } else { 
    
            // If this is a new part 
            // and not a split character
            // we make a new pointer
            if ( newPart == 1 ){
              // if reach maxpart we break.
              // It is okay here, to not worry about memory
              if ( partSize == maxParts ) break;
              parts[partSize++] = &mem[len];
              newPart = 0;
            }
    
            mem[len++] = string[i];
    
            if ( len == size ){
              // if ran out of memory realloc.
              tempMem = (char*)realloc(mem, sizeof(char) * (size << 1)  ); 
              // if fail quit loop
              if ( tempMem == NULL ) {
                // If we can't get more memory the last part could be corrupted
                // We have to return.
                // Otherwise the code below can seg.
                // There maybe a better way than this.
                return partSize--;
              }
              size = size << 1;
              mem = tempMem;
            }
          }
        }
    
        // If we got here and still in a newPart that is fine no need 
        // an additional character.
        if ( newPart != 1 ) mem[len++] = 0;
    
        // realloc to give back the unneed memory
        if ( len < size ) {
          mem = (char*) realloc(mem, sizeof(char) * len );
        }
    
        return partSize;
    }
    
    int main(){
        char * tStr = "This is a super long string just to test the str str adfasfas something split";
        char * parts[10];
    
        int len = split(tStr, ' ', parts, 10);
    
        for (int i = 0; i < len; i++ ){
          printf("%d: %s\n", i, parts[i]);
        }
    }
    
    0 回复  |  直到 6 年前