69,382
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<string.h>
#include<malloc.h>
// 用来保存多个字符串的结构
typedef struct
{
size_t len;
char *str[0];
} Strings;
int main()
{
char teststring[] = "a bc defg hij klmn op"; //测试字符串
Strings* maxlength_strings=NULL; // 用来保存多个字符串
size_t maxlength = 1; // 最大长度
size_t wordcount = 1; // 统
char* p = teststring; // 计
while (p = strpbrk(p, " ")) // 单
{ // 词
++wordcount; // 总
++p; // 个
} // 数
maxlength_strings = (Strings*)calloc(1,sizeof(Strings) + sizeof(char*)*wordcount);
if (maxlength_strings)
{
// strtok 用于分割字符串,详见http://en.cppreference.com/w/c/string/byte/strtok
for (p = strtok(teststring, " "); p; p = strtok(NULL, " "))
{
size_t len = strlen(p);
if (len > maxlength) // 如果更长,则重置maxlength_strings
{
maxlength = len;
maxlength_strings->len = 1;
maxlength_strings->str[0] = p;
}
else if (len == maxlength) // 如果与最长的同样长,则添加到maxlength_strings
maxlength_strings->str[maxlength_strings->len++] = p;
}
{
size_t i;
for (i = 0; i < maxlength_strings->len; ++i) // 输出maxlength_strings里的所有字符串
puts(maxlength_strings->str[i]);
}
free(maxlength_strings);
}
return 0;
}
输出:defg
klmn
#include<stdio.h>
#include<string.h>
int main(void)
{
char str[] = "I love you baby";
char *words[256];
char *p;
int i = 0, j;
for (p = strtok(str, " "); p; p = strtok(NULL, " "))
{
words[i++] = p;
}
int len = 0, pos;
for (j = 0; j<i; j++)
{
if (strlen(words[j]) > len)
{
len = strlen(words[j]);
pos = j;
}
}
printf("max length word is \"%s\", len=%d\n", words[pos], len);
return 0;
}
//max length word is "love", len=4
#include <stdio.h>
int main()
{
char str[]="this is a book with other and me tomrrow";
char* p;
char* q;
char* index;
int len=0;
for(p=q=str;*p;)
{
for(;*p!=' '&&*p;p++);
if(p-q>len)
{
len=p-q;
index=q;
}
p++;
q=p;
}
for(;*index!=' '&&*index;index++)
{
printf("%c",*index);
}
return 0;
}
for(p=strtok(str, " "); p; p=strtok(NULL, " "))
{
words[i++]=p;
}
#include<stdio.h>
#include<string.h>
int main(void)
{
char str[]="I love you baby";
char *words[256];
char *p;
int i=0, j;
for(p=str; p=strtok(NULL, " "); )
{
words[i++]=p;
}
int len=0, pos;
for(j=0; j<i; j++)
{
if(strlen(words[j]>len)
{
len=strlen(words[j]);
pos=j;
}
}
printf("max length word is %s, len=\n", words[pos], len);
return 0;
}