一段解析字符串中单词的C语言小程序

// 解析字符串中单词的小程序,方便实用
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>

int word_clear(char *word[], int n)
{
	if (n < 0)
	{
		return -1;
	}

	for (int i = 0; i < n; i++)
	{
		if (word[i] != NULL)
		{
			free(word[i]);
			word[i] = NULL;
		}
	}

	return 0;
}


bool word_is_found(char *w[], int n, char *s)
{
	if (NULL == w || NULL == s)
	{
		return false;
	}

	if (n < 0)
	{
		return false;
	}

	for (int i = 0; i < n; i++)
	{
		if ( 0 == strcmp(w[i], s))
		{
			return true;
		}
	}

	return false;
}

int str_word_stat(char *s, char *word[], int *n)
{
	char *p = NULL;
	char *ps = NULL;
	char *pw = NULL;

	if (NULL == s || NULL == word || NULL == n)
	{
		return -1;
	}

	p = s;
	while (!isalpha(*p))
	{
		p++;
	}
	while (*p != '\0')
	{
		ps = p;
		while (isalpha(*p))
		{
			p++;
		}

		pw = (char *)malloc(p -ps + 1);
		if (NULL == pw)
		{
			word_clear(word, *n);
			return -1;
		}
		
		memset(pw, '\0', p - ps + 1);
		strncpy(pw, ps, p - ps);
		if (word_is_found(word, *n, pw))
		{
			free(pw);
		}
		else
		{
			word[(*n)++] = pw;
		}
		
		while (!isalpha(*p) && (*p != '\0'))
		{
			p++;
		}
	}

	return 0;
}


int main(void)
{
	char s[] = "i am a boy, what about you? i see you today!";
	char *w[1024]= { NULL };
	int n  = 0;

	word_clear(w, 1024);

	str_word_stat(s, w, &n);

	for (int i = 0; i < n; i++)
	{
		printf("%s\n", w[i]);
	}

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值