在C中,如何将存储在变量中的多个单词字符串分解为一个数组,每个单词都包含一个数组值

时间:2015-10-03 01:53:39

标签: c arrays string parsing

我要做的是让用户输入多个单词,这些单词当前在一个变量中分开,每个单词存储在一个数组值中。

例如,用户输入以下内容:“在课程中时” 它存储在单个变量“input”

如何将该变量的每个单词都变成这样的数组:

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

我的最终目标是能够针对输入的第一个单词运行if语句,并使用它来确定后续操作的过程。

例如用户输入:在课程中添加

我对它运行一个if语句:

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

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

然后删除等。

谢谢你们的帮助。

2 个答案:

答案 0 :(得分:2)

我不太了解你的问题,但我会先从这个功能开始,所以你可以拆分你的字符串:

  

C库函数char * strtok(char * str,const char * delim)   使用分隔符delim将字符串str分解为一系列标记。

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

参数str - 修改并破坏此字符串的内容   分成较小的字符串(标记)。

     

delim - 这是包含分隔符的C字符串。这些可能   因呼叫而异。

source

答案 1 :(得分:1)

我会在开头使用strtok。我知道这是很多代码,但我写了它,向您展示如何正确管理动态分配的内存以及如何正确使用strtokrealloc等功能,因为您看到了很多错误的用法这些功能。

当然,你可以通过更高的性能让它更好,但就像我说的,我想向你展示如何使用动态分配的内存。

#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;
}

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)
相关问题