简体   繁体   中英

In C how do I break a multiple word string stored in a variable into an array with each word holding an array value

What I am looking to do is have a users input of multiple words which is currently in one variable split apart and each of the words stored in an array value.

For example a user types input of: "When in the course" and it's stored in a single variable "input"

How do I get each word of that variable into an array like such:

array[0] = When
array[1] = in
array[2] = the
array[3] = course
etc.

My end goal is to be able to run an if statement against the first word typed and use it to determine the course of action for what follows.

For example the user types: ADD when in the course

and I run an if statement against it:

if array[0] = ADD
then  file_ptr = fopen ("file1.txt", "a+");

            fprintf(file_ptr, "%s" , buf," ");
                    }
            fclose(file_ptr);
else if array[0] = delete

then delete etc.

Thank you guys for the assistance.

I don't understand your question very well, but I would start with this function first, so you can split your string:

The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.

char *strtok(char *str, const char *delim)

Parameters str -- The contents of this string are modified and broken into smaller strings (tokens).

delim -- This is the C string containing the delimiters. These may vary from one call to another.

source

I would use strtok at the beginning. I know this is a lot of code, but I wrote it showing you how to correctly manage dynamic allocated memory and how to correctly use functions like strtok and realloc , because you see a lot of wrong usage of these functions.

Of course you can make it better with more performance, but like I said, I wanted to show you more how to use dynamic allocated memory.

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

char *copy_str(const char *str)
{
    if(str == NULL)
        return NULL;

    char *ptr = malloc(strlen(str) + 1);
    if(ptr)
    {
        strcpy(ptr, str);
        return ptr;
    }
    return NULL;
}

char **add_new_word(char **words, char *newword)
{
    int len;
    for(len=0; words && words[len]; ++len);

    char **tmp = realloc(words, (sizeof *words)*(len + 2));
    if(tmp == NULL)
        return NULL;
    tmp[len] = newword;
    tmp[len+1] = NULL;
    return tmp;
}


char **get_words(const char *sentence)
{
    char **strings = NULL, **tmp_strings;
    char *tmp_sentence = copy_str(sentence);
    char *tmp_sentence_orig = tmp_sentence;
    if(tmp_sentence == NULL)
        return NULL;

    char *tmp_word = copy_str(strtok(tmp_sentence, " "));
    if(tmp_word == NULL)
    {
        free(tmp_sentence_orig);
        return NULL;
    }

    tmp_strings = add_new_word(strings, tmp_word);
    if(tmp_strings == NULL)
    {
        free(tmp_sentence_orig);
        return NULL;
    }
    strings = tmp_strings;

    while(tmp_word = copy_str(strtok(NULL, " ")))
    {
        tmp_strings = add_new_word(strings, tmp_word);
        if(tmp_strings == NULL)
        {
            free(tmp_word);
            free(tmp_sentence_orig);
            return strings; // got all words we could
        }
        strings = tmp_strings;
    }

    free(tmp_sentence_orig);
    return strings;
}

void free_words(char **words)
{
    if(words == NULL)
        return;

    int i;
    for(i=0; words[i]; ++i)
        free(words[i]);

    free(words);
}

int main(void)
{
    char **words = get_words("When in the course");

    if(words == NULL)
        return 1;

    int i;
    for(i = 0; words[i]; ++i)
        printf("word #%d: '%s'\n", i+1, words[i]);

    free_words(words);
    return 0;
}

as you can see from valgrind :

==31202== Memcheck, a memory error detector
==31202== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==31202== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==31202== Command: ./a
==31202==
word #1: 'When'
word #2: 'in'
word #3: 'the'
word #4: 'course'
==31202==
==31202== HEAP SUMMARY:
==31202==     in use at exit: 0 bytes in 0 blocks
==31202==   total heap usage: 9 allocs, 9 frees, 150 bytes allocated
==31202==
==31202== All heap blocks were freed -- no leaks are possible
==31202==
==31202== For counts of detected and suppressed errors, rerun with: -v
==31202== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM