在跳过空格的同时遍历字符数组

Iterate through a character array while skipping over whitespace

我正在尝试编写一个程序来遍历字符数组(其中包含一个句子),并将该句子中的单词分配给另一个数组,跳过空格(这就是我们认识单独单词的方式),然后打印这些词。

例如我的字符数组是:

{'t','h','e',' ','f','o','x',' ','r','u','n','s','[=10=]',}

我希望我的函数将单词分配给一个数组,称之为 words,一次一个,跳过空格,然后一个一个地打印单词。

我试过这个:

for (i = 0, x = 0; a[i] != '[=11=]'; i++, x++){
    if (a[i] != ' '){
        words[x] = a[i];
    }
    else{
        words[x] = '[=11=]';
            printf("%s\n", words);
            x=0;
            i++;
            continue;
        }
    }
    printf("%s\n", words);

但是当我运行它时,它只打印出s

使用 continue in for 循环,您不需要 i++,您需要设置 x=-1

for (i = 0, j = 0; a[i] != '[=10=]'; i++, x++){
    if (a[i] != ' '){
        words[x] = a[i]; // U need to use j
    }
    else{
        words[x] = '[=10=]';
             printf("%s\n", words);
            x=-1; // as you are using continue
            // i++; You don't need this
            continue;
        }
    }
     printf("%s\n", words);

我的建议是strtok()。会容易很多。

想法:

  1. 使用strtok()和space' '作为分隔符找出每个出现的.
  2. 使用strcpy()复制将返回的tokens(words)复制到word数组中。

注:

I want my function to assign the words to an array, call it words, one at a time, skipping over the spaces, the words then printed one by one.

您当前的代码看起来不一样。

  1. 您可以摆脱遍历输入字符串的 for 循环。
  2. 您需要在同一输入上继续 strtok(),直到返回 NULL
  3. words[x] 需要是 char *(具有正确分配的内存)或 char [](数组)来保存从中找到的每个 word输入字符串,然后一一打印。

这是完整的程序吗?

words[x] = a[i];

您可能希望将 words[x] 放入一个循环中,每次您找不到空格时递增 x 1

好的,我注意到您已经对其进行了编辑。另外,它是一个数组,所以我想你需要遍历数组并打印每个字符。

用于打印,

for (j = 0; j < sizeof(words)/sizeof(words[0]); j++ )
    {
        printf("%c", words[j] );
    }

注意在main之外定义的变量(数组a除外,它被显式设置为字符串)编译器默认置零,不需要显式初始化,但是一般来说,您必须非常小心初始化,尤其是在函数内部。

a,虽然定义为指向字符串文字的指针,但也可以作为字符数组访问。

输出:

words[0] = the
words[1] = fox
words[2] = runs

这个有效:

#include <stdio.h>

#define MAX_WORDS 1000
#define MAX_WORD_LEN 32
char *a = "the fox runs";
char words[MAX_WORDS][MAX_WORD_LEN];
int i, j, k;

int
main(void) 
{
    for (i = 0; k < MAX_WORDS && a[i] != '[=11=]'; i++) {
        if (a[i] != ' ' && j <= 32) {
            words[k][j++] = a[i];
        } else {
            words[k++][j] = '[=11=]';
            printf("words[%d] = %s\n", k - 1, words[k - 1]);
            j = 0;
        }
    }
    printf("words[%d] = %s\n", k, words[k]);
}