有一段文本,将文本中的所有单词存放到一个字符串数组中

#import <Foundation/Foundation.h>

#define IS_NOT_LETTER(C) (!((C>='a' && C<='z') || (C>='A' && C<='Z')))

//获取单词个数

int getWordNumber(char * text){

    int count = 0;

    while (*text != '\0' ) {

        

        if (IS_NOT_LETTER(*text)) {

            count ++;

        }

        text ++;

    }

    

    return count;

}


int main(int argc, const char * argv[])

{

    //一段文本

    char text[] = "Whenever you create a primitive that can have a variable number of output terminals,create them as you go,to ensure that all possible paths of flow are apparent.";

    //获取单词个数

    int wordCount = getWordNumber(text);

    typedef char * P_CHAR;

    //给数组分配堆内存

    P_CHAR * words = malloc(sizeof(P_CHAR)*wordCount);

    

    

    //获取每个单词,并给数组分配内存空间

    unsigned long wordLength = 0;

    char *pStart = text;

    char *pEnd = text;//循环指针

    int iword = 0;//单词在数组中的下标

    while (*pEnd != '\0') {

        if (IS_NOT_LETTER(*pEnd)) {//如果指向非字母

            //得到单词长度

            wordLength = pEnd - pStart;

            //为当前单词分配内存

            words[iword] = malloc(wordLength + 1);

            memset(words[iword], 0, wordLength +1);//内存空间清零

            memcpy(words[iword], pStart, wordLength);//复制到数组中

            pStart = pEnd + 1;

            iword ++;

            

        }

        pEnd ++;

    }

    

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

        printf("%s\n",words[i]);

        free(words[i]);

    }

    free(words);

    

    

    return 0;

}


展开阅读全文

没有更多推荐了,返回首页