/求最长单词
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
#include<ctype.h>
void MaxWord(const char *str)
{
int max = 0;//记录最长单词的字符数,计数器
int cur = 0;//记录当前单词的字符数
char* maxstr = (char *)malloc(sizeof(char) * (strlen(str)+1));//开辟空间,存储最长单词,要大于字符串长度,防止越界
char* curstr = (char *)malloc(sizeof(char) * (strlen(str)+1));//开辟空间,存储当前单词,要大于字符串长度,防止越界
if(maxstr == NULL || curstr == NULL) exit(0);
while(*str != '\0')
{
if(isalpha(*str))//判断是否为字母
{
curstr[cur] = *str;//赋值给当前单词
cur++;//当前单词字符数++
}
else
{
if(cur > max)//判断当前单词字符数是否大于最长单词
{
curstr[cur] = '\0';//加上\0表示字符串
strcpy(maxstr,curstr);//调用字符串拷贝函数
max = cur;//把当前字符数赋值给最大值
}
cur = 0;//把当前单词字符数置0
}
str++;//指针++
}
printf("maxstr = %s\n",maxstr);
printf("max = %d\n",max);
free(curstr);//函数结束,释放动态开辟内存
free(maxstr);
}
int main()
{
char *str = "i am a student!";
MaxWord(str);
char *str1 = "he is like a dog.";
MaxWord(str1);
char *str2 = "i adore you";
MaxWord(str2);
char *str3 = "The book is mine ";
MaxWord(str3);
char *str4 = " ";
MaxWord(str4);
return 0;
}
///统计字符串中的英文字母,空格,数字,其他字符
void Count(const char *str)
{
int alpha = 0;//英文单词数
int blank = 0;//空格数
int digit = 0;//数字
int other = 0;//其他字符
assert(str != NULL);
for(int i = 0;str[i] != '\0';i++)
{
if(isalpha(str[i]))
{
alpha++;
}
else if(str[i] == ' ')
{
blank++;
}
else if(isdigit(str[i]))
{
digit++;
}
else
{
other++;
}
}
printf("英文字母个数 = %d\n",alpha);
printf("空格个数 = %d\n",blank);
printf("数字个数 = %d\n",digit);
printf("其他字符个数 = %d\n",other);
printf("\n");
}
int main()
{
char *str = "i am a student!";
Count(str);
char *str1 = " ";
Count(str1);
char *str2 = " ";
Count(str2);
char *str3 = "\0";
Count(str3);
char *str4 = "++ -- . //1 ";
Count(str4);
Count_Word(str);
return 0;
}
求单词数
void Count_Word(const char *str)
{
int count = 0;
assert(str != NULL);
if(str == '\0')
{
printf("str is a nullstr\n");
}
for(int i = 0;str[i] != '\0';i++)
{
if(isalpha(str[i]) && !isalpha(str[i+1]))
{
count++;
}
}
printf("单词个数:%d\n",count);
}
int main()
{
char *str = "i am a student!";
Count_Word(str);
char *str1 = "";
Count_Word(str1);
char *str2 = "haha";
Count_Word(str2);
return 0;
}