C语言 求输入一行字符串,查找其中最长的单词

相关代码如下,
为了省辅助空间,没有另外定义数组。这里需要注意在原来字符串上的操作,注意防止字符串的截断(使用’\0’,使后边的字符串无法读取)。

#define MAXSIZE 1024
int main(int argc, char *argv[])
{	
	char str[MAXSIZE];
	int count=0;
	int max=0;
	int i=0;
	char *array=NULL;
	gets(str);   //输入一行字符串
	puts(str);   //显示输入的字符串
	while(str[i]!='\0'){
		if(str[i]>64&&str[i]<91||str[i]>96&&str[i]<123){    //a~z  A~Z
	  		count++;    //记录字符串长度
		}else{
	   		if(max<count){
	    	  		max=count;   //如果记录的字符串长度超过原来max长度,则将count赋值给max
	       		array=&str[i-count];    //将指针array指向str中最长单词首位
 	   		} 
	   		count=0;         //记录字符串清空,等待记录下一个单词长度
	   	}
	   	i++;
	}
	printf("the long worlds:\t");
	for(i=0;i<max;i++){    		//这里是重点,用while循环不太好,因为需要一个标记,若设置一个array[i]!='\0',则会将原有字符串截断,
							//另外,若没有'\0',那么最长单词如果在中间,那么会将后边单词也输出。另外若有特殊符号,也会输出,
							//所以用for循环,直接确定多长,直接输出
		putchar(array[i]);	
	}
	printf("\nmax:   %d\n",max);
	return 0;
}
发布了15 篇原创文章 · 获赞 0 · 访问量 223

猜你喜欢

转载自blog.csdn.net/ren_x_guo/article/details/104836505