程序分析:
可以定义两个字符串,一个用来存放字符串,一个用来存储最长的单词。通过比较得到最长的单词,再通过元素下标来获取最长的单词。
#include "stdio.h" #include "string.h" int main(void) { //定义两个数组,sentence储存字符串,word存储单词 char sentence[1024] = {}, word[64] = {}; //length:单词长度;index:字符串下标 int length = 0, index = 0; int max = 0, k = 0; printf("please input a sentence:"); //fgets():从键盘获取字符串 fgets(sentence, 1024, stdin); //循环直到字符串结束 for (int i = 0; sentence[i] != '\0'; i++) { length = 0; //获取一个单词的长度 for (k = i; sentence[k] != ' ' && sentence[k] != '\0'; k++) { length++; index++; } //判断当前单词长度是否大于已判断的最大单词长度 if (length >= max) { //清空word数组 memset(word, '\0', sizeof(max)); max = length; for (int j = 0; j<length; j++) { word[j] = sentence[index - length + j]; } index++; i = k; } } puts(word); return 0; }