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

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

}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值