69,373
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include "string.h"
#include "malloc.h"
int main()
{
int i,j,k,t;
int max = 0;
char *p = NULL;
char str[42] = "2xtzuaojy5678zuaojy908pzuaojy417zuaojy356";
char temp[8];
char result[8];
memset(result,0,8);
p = str;
for(i=0;i <42;i++)
{
for(j=i+1;j <42;j++)
{
if(*(p+i)== *(p+j))
{
t = i;
k = 0;
memset(temp,0,8);
//只要找到了相同的首字符,就开始比较直到没有相同的字符,记录当前字符串,看是否是最长的
while(*(p+t)== *(p+j))
{
temp[k] = *(p+t);//不断比较后续的字符
t++;
j++;
k++;
}
if(k > max)//将最长的字符串赋值给result
{
max = strlen(temp);
strcpy(result,temp);
}
}
}
}
//打印出结果在上述字符串中最长的是 "zuaojy"
printf("最长单词是 %s,长度为 %d \n",result,max);
return 0;
}
//那就这样吧!
#include <stdio.h>
#include <string.h>
int main()
{
char pstr[] = {"this, is-text_marry. example!"};
char *sepa = {" ,\t\n\v\f!._-"};
char *token = NULL;
int max_len = 0, dff = 0;
char *tmp = NULL;
token = strtok(pstr, sepa);
while (token != NULL)
{
dff = strlen(token);
if (max_len < dff)
{
max_len = dff;
tmp = token;
}
token = strtok(NULL, sepa);
}
printf("size: %d\nmax_word: %s\n", max_len, tmp);
}
//就是利用 C++的string的一些操作
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("this is test marry, example!");
string token(" ,\t:\v\n\f!.");
string::size_type pos = 0, end = 0, max_len = 0, dff = 0;
string tmp1;
while ((pos = str.find_first_not_of(token, end))//找出第一个不是token里面的下标
!= string::npos)
{
end = str.find_first_of(token, pos);//找出第一个是token里面的下标
if (end == string::npos)//两个下标相减就是距离了
{
dff = str.size() - pos;
}
else
{
dff = end - pos;
}
if (max_len < dff)
{
max_len = dff;
tmp1.assign(str, pos, dff);
}
}
cout << "size: " << max_len << endl;
cout << tmp1 << endl;
}
#include<stdio.h>
#include<windows.h>
//select_word对于有多个长度相同的单词只取了第一个作为返回值
char *select_word(char *str) //参数:待处理的字符串
{
unsigned int max=0, len=0;
char *temp=str, *result=NULL;
do
{
if((*temp>='a'&&*temp<='z')||(*temp>='A'&&*temp<='Z'))
len+=1;
else
{
if(len>max)
{
max=len;
str=temp-len;
}
len=0;
}
}while(*temp++);
result=(char *)malloc(max+1);
sscanf(str,"%[a-zA-Z]",result);
result[max]='\0';
return result; //提取出来的最长的单词
}
int main()
{
char *pt, *pstr="Hellow, welcom to BeiJing!";
pt=select_word(pstr);
printf("%s\n",pt);
free(pt);
return 0;
}