方法一:
#include<string.h>
int find_longest(char line[])//把数组传过来
{int is_alphabetic(char word);int i = 0;int length = 0;//统计每个字符串的长度int max = 0;//比max长就把值赋值给maxint place = 0;//最长单词的起始位置int point;//每个字符串第一个字符的下标for (i = 0; i <= strlen(line); i++)//字符有空格和'\0'{if (is_alphabetic(line[i])){length++; }else //遇到空格或'\0'{point = i - length;if (length >= max) //输入的字符串万一有相等的呢?{place = point;max = length;}length = 0;//重新统计下一个字符串长度}}return place;
}
int is_alphabetic(char word)//word形参,接收数组传来的实参line[i]
{if ((word >= 'a' && word <= 'z' )|| (word >= 'A' && word <= 'Z'))return 1;//是字母,返回1。elsereturn 0;//不是,返回0。
}
int main()
{int find_longest(char line[]);int is_alphabetic(char word);char line[100];int i = 0;printf("input one line:\n");gets(line);//输入可能不是单词,是空格,所以写一个函数判断printf("The longest word is:\n");for (i = find_longest(line); is_alphabetic(line[i]); i++)printf("%c", line[i]);printf("\n");return 0;
}
方法二:(错误),自己到时改正了会修改
#include<string.h>
void LongestWord(char str[], char word[])
{int max_len = 0;int len = 0;int i = 0;while (str[i] != '\0'){if (str[i] == ' '){str[i] = '\0';len = strlen(str);if (len > max_len){max_len = len;strcpy(word, str);str = str + len + 1;}}i++;}
}
int main()
{char line[100] = { 0 };char word[100] = { 0 };printf("input one line:\n");gets(line);LongestWord(line, word);printf("The longest word is : %s\n", word);return 0;
}
方法三:
#include<string.h>
void findlong(char str[], char word[]) {int i = 0, j = 0;int len = 0;while (str[i] != '\0') {j = i;while (str[j] != ' ' && str[j] != '\0')j++;len = j - i;if (len > strlen(word)){strncpy(word, str + i, len);//拷贝临时最长单词 }j++;i = j;}
}
int main()
{char str[100] = { 0 };printf("请输入一个字符串:\n");gets(str);char word[20] = { 0 };findlong(str, word);printf("这个字符串最长单词为:\n%s\n", word);return 0;
}
方法四 :
#include<ctype.h>
#include<string.h>//获取最大单词
char CurWord[100];
char MaxWord[100];char* Get_MaxWord(const char* str)
{int len_cur = 0;//保存临时单词空间内的长度int len_max = 0;//保存最大单词空间内的长度while (*str != '\0'){if (isalpha(*str))//如果为真 代表指针str指向的字符是一个字母字符{CurWord[len_cur++] = *str;}else{if (len_cur > len_max){strcpy(MaxWord, CurWord);len_max = len_cur;//len_cur = 0;}len_cur = 0;}str++;}if (len_cur > len_max){strcpy(MaxWord, CurWord);}return MaxWord;
}
int main()
{char arr[100];printf("请输入一个字符串:\n");const char* str = gets(arr);printf("这个字符串最长单词为:\n%s", Get_MaxWord(str));return 0;
}