welcome: please sign in
location: FH-Rosenheim / Programmieren_1 / Teilen_von_Strings_variabler_Länge

Teilen von Strings variabler Länge

split.h

#ifndef GUARD_SPLIT_H
#define GUARD_SPLIT_H

typedef enum { false = 0, true = 1} bool;

char **splitsep(const char *line, int *num_of_words, const char sep);
char **split(const char *line, int *num_of_words);
void Assert(const bool b, const char *message);

#endif

split.c

#include "split.h"

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

char **splitsep(const char *line, int *num_of_words, const char sep)
{
    int i = 0;
    int j = 0;
    // array for holding the separate words
    char **words;
    *num_of_words = 0;

    while(line[i] != '\0')
    {
        // discard leading whitespace
        while(line[i] != '\0' && line[i] == sep)
            i++;

        j = i; // j marks the beginning of the word

        // search 'sep' after the word
        while(line[i] != '\0' && line[i] != sep)
            i++;

        // are there any chars to copy?
        if(i != j)
        {
            // alloc memory for one line == memory for one pointer
            if(*num_of_words == 0)
            {
                words = malloc(1 * sizeof(char *));
                Assert(words != NULL, "malloc() error (\"line\")\n");
            } else
            {
                words = realloc(words, (*num_of_words+1)*sizeof(char *));
                Assert(words != NULL, "realloc() error (\"line\")\n");
            }
            // allocate memory for (i-j + '\0') character
            words[*num_of_words] = (char*) malloc((i-j+1) * sizeof(char));
            Assert(words[*num_of_words] != NULL, 
                   "malloc() error (\"chars\")\n");
            
            // copy i-j chars, beginning at &line[j] to words[num_of_words]
            strncpy(words[*num_of_words], &line[j], i-j);
            // add terminating '\0'
            words[*num_of_words][i-j] = '\0';
            
            (*num_of_words)++;
            // advance one word
            j = i;
        }
    }
    return words;
}

char **split(const char *line, int *num_of_words)
{
    return splitsep(line, num_of_words, ' ');
}

void Assert(const bool b, const char *message)
{
    if(!b)
    {
        printf(message);
        exit(1);
    }
}

so könnte man das ganze benutzen:

#include <stdio.h>
#include <stdlib.h> // free()
#include "split.h"

int main()
{
    const char *words1 = "Hallo ich bin zum Teilen da";
    char **splitted1;
    int split1_count, i;

    splitted1 = split(words1, &split1_count);

    for(i = 0; i < split1_count; i++)
        printf("%s\n", splitted1[i]);
    printf("\n");

    for(i = 0; i < split1_count; i++)
        free(splitted1[i]);
    free(splitted1);

    return 0;
}

Hier der Source als tar.bz2 Datei: split-0.2.tar.bz2

FH-Rosenheim/Programmieren_1/Teilen_von_Strings_variabler_Länge (last edited 2008-07-14 09:55:40 by localhost)