第1个回答 2010-03-09
我新写了一个,你看下吧, 主要用到了strtok()这个函数, 这个函数在做字符串切割时很有用的...
/*问题描述:
C语言 在字符串中找到最长单词
*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define MAX_STRING_LEN 100
void findTheMaxLen(char* string)
{
char* buf = NULL;
char* temp = NULL;
int preStringLen = 0;
for(temp = strtok(string, " "); temp; temp = strtok(NULL, " "))
{
preStringLen = strlen(temp);
buf = (char*)malloc((preStringLen + 1) * sizeof(char));
memset(buf, '\0', (preStringLen + 1) * sizeof(char));
if(strcmp(temp, buf) > 0)
strcpy(buf, temp);
}
printf("最长的字符串是: %s\n", buf);
free(buf);
buf = NULL;
}
void main()
{
char string[MAX_STRING_LEN] = {'\0'};
printf("请输入一个字符串: \n");
gets(string);
findTheMaxLen(string);
}本回答被提问者采纳
第2个回答 2010-03-09
#include "stdio.h"
#include "string.h"
void main()
{
char str[100];
int maxLength=0,length=0,index,i;
printf("input:\n");
gets(str);
for(i=0;str[i];i++){
if(str[i]!=' ') {
length++;
if(length>maxLength){
index=i;
maxLength=length;
}
}else{
length=0;
}
}
printf("the longest string is:\n");
for(i=maxLength;i!=0;i--){
printf("%c",str[index-i+1]);
}
}
第3个回答 2010-03-09
#include<stdio.h>
#include<conio.h>
#include<string.h>
void p(char ch[80])
{
int i=-1,j=0;
int start=0,mark=0;
int len=0,maxlen=0;
char out[80];
memset(out,sizeof(out),0x00);
do
{
i++;
if(ch[i]!=' '&&ch[i]!=0)
{
len++;
}
else
{
maxlen=len;
mark=i;
len=0;
}
}while(ch[i]!=0);
start=mark-maxlen;
for(i=0;i<maxlen;i++)
{
out[i]=ch[i+start];
}
out[i+1]=0;
printf("%s",out);
}
int main()
{
char c[80];
gets(c);
p(c);
getch();
return 0;
}
第4个回答 2010-03-09
何必那么复杂,一边扫描输入字符串,一边计算当前单词的长度,如果当前单词的长度大于记录的长度,就把当前单词存下来,看我的例程吧。(我的算法判断是否是单词的依据是,只要不是英文字母的字符,就是单词分割符,比如空格,逗号,句号,叹号之类都是分隔符)
函数 isalphabetic 的作用是判断一个字符是否是26个英文字母中的一个, 函数 func 的作用是扫描输入字符串,找到最长的那个单词并打印。
#include <stdio.h>
#include <string.h>
int isalphabetic(char ch)
{
if ((ch >= 'a' && ch <= 'z')||(ch >= 'A' && ch <= 'Z'))
{
return 1;
}
return 0;
}
void func(char *pStr)
{
int i, j;
int max_len = 0, cur_len;
char result[80];
memset(result, 0, sizeof(result));
for(i = 0; pStr[i] != '\0'; )
{
if (isalphabetic(pStr[i]))
{
for (j = i; pStr[j] != '\0'; j++)
{
if (!isalphabetic(pStr[j]))
break;
}
if (max_len < (j - i))
{
max_len = (j - i);
strncpy(result, &pStr[i], (j-i));
result[j-i] = '\0';
}
i = j;
}
else
{
i++;
}
}
if (max_len > 0)
printf("Longest word is \'%s\'\n", result);
}
int main()
{
char c[80];
gets(c);
func(c);
return 0;
}