將一篇文本中的單詞保存在一個字符串數組中

 char string[] = "I love ios I want to make an project zpp lanou";

    char * strs[255] = {0};

    int i = 0,count = 0; int wordcount = 0;

    while (*(string + i) != '\0') {

        char temp[100] = {0};int k = 0;static int m = 0;


        if (*(string + i)!= ' ') {

            count++;

        }

        else{

            char * str = malloc(count + 1);

            wordcount++;

            for (int j = i - count;j < i;j++) {

                *(temp + k) = *(string + j);

                k++;

            }

            strcpy(str, temp);

            strs[m] = str;

            m++;

            count = 0;

        }

        if (*(string + i + 1) == '\0') {

            char * str = malloc(count + 1);k = 0;

            wordcount++;

            for (int j = i - count;j <= i;j++) {

                *(temp + k) = *(string + j);

                k++;

            }

            strcpy(str, temp);

            strs[m] = str;

            free(str);

            str = NULL;

        }

        i++;  ///!!!!!!!!!!!!!    在while循環一定不要忘了!!!!!!!!!!!!!!!!!

    }

    for (int i = 0; i < wordcount; i++) {

        printf("%s\t", strs[i]);

    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章