gpt4 book ai didi

c - 查找字符串中最长的单词

转载 作者:行者123 更新时间:2023-11-30 14:37:36 24 4
gpt4 key购买 nike

我对 C 编码很陌生。我已经编写了代码来查找字符串中最长的单词。我的代码没有显示任何错误,但它打印了一个带有不在字符串中的奇怪字符的单词。你能告诉我我的代码有什么问题吗?谢谢

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char LongestWord (char GivenString[100]);

int main()
{
char input[100];
char DesiredWord[20];

printf("please give a string:\n");
gets(input);
DesiredWord[20]=LongestWord(input);

printf("longest Word is:%s\n",DesiredWord);

return 0;
}

char LongestWord (char GivenString[100]){
//It is a predefined function, by using this function we can clear the data from console (Monitor).
//clrscr()
int position1=0;
int position2=0;
int longest=0;
int word=0;
int Lenght=strlen(GivenString);
char Solution[20];
int p=0;

for (int i=1; i<=Lenght; i++){
if (GivenString[i-1]!=' '){
word=word++;
}
if(GivenString[i-1]=' '){
if (word>longest){
//longest stores the length of longer word
longest=word;
position2=i-1;
position1=i-longest;
word=0;
}
}
}
for (int j=position1; j<=position2; j++){
Solution[p]=GivenString[j];
p=p++;
}
return (Solution[20]);
}

最佳答案

这应该有效:

#include <stdio.h>
#include <string.h>

void LongestWord(char string[100])
{
char word[20],max[20],min[20],c;
int i = 0, j = 0, flag = 0;
for (i = 0; i < strlen(string); i++)
{
while (i < strlen(string) && string[i]!=32 && string[i]!=0)
{
word[j++] = string[i++];
}
if (j != 0)
{
word[j] = '\0';
if (!flag)
{
flag = !flag;
strcpy(max, word);
}
if (strlen(word) > strlen(max))
{
strcpy(max, word);
}
j = 0;
}
}
printf("The largest word is '%s' .\n", max);

}


int main()
{
char string[100];
printf("Enter string: ");
gets(string);
LongestWord(string);
}

关于c - 查找字符串中最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57212190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com