给一个字符串、例如 “ababc”要求返回“ab”,因为“ab”连续重复出现且最长。
#include <stdlib.h>实现strrev
char *match(char *s, char *pattern, int n)
{
char *ps, *p, *q, i;
for ( ps = s; *ps != 0; ++ps )
{
p = ps;
q = pattern;
i = 0;
while ( *q++ == *p++ && i < n ) ++i;
if ( n == i ) return ps;
}
return NULL;
}
int strlen(char *s)
{
int n = 0;
while (*s++ != 0 ) ++n;
return n;
}
char *strrep(char *s, char *buf)
{
int i, j, n, m, k;
int l = strlen(s);
n = l/2;
for ( i = n; i >= 2; --i )
{
m = l - i;
for ( j = 0; j <= m-i; ++ j )
{
for ( k = j + i; k <= m; ++ k )
{
if ( match(s+k, s+j, i) != 0 )
{
memcpy(buf, s+j, i);
buf[i] = 0;
return buf;
}
}
}
}
return NULL;
}
int main()
{
char s[80], b[80];
write(1, "s:", 2);
gets(s);
printf("max: %s/n", strrep(s, b));
}
#include <stdlib.h>实现strstr
void _strrev(char *dst, char *src, char *send)
{
char *p, *q;
for (p = send, q = dst; p != src; )
*q++ = *p--;
*q = *p;
}
void _strrev2(char *p1, char *p2)
{
char c;
for ( ; p1 < p2; p1++, p2--)
{
c = *p1;
*p1 = *p2;
*p2 = c;
}
}
char *strrev(char *dst, char *src)
{
char *p, *q;
int n;
if ( dst == NULL || src == NULL ) return NULL;
if ( *src == 0 ) return dst;
for (p = src, n = 0; *p != 0 ; ++p, ++n);
if ( src == dst ) {
_strrev2(src, p-1);
}
else if ( dst >= p || dst+n<=src) _strrev(dst, src, p-1);
else if ( dst < src ){
_strrev(dst, dst+n, p-1);
_strrev2(src, dst+n-1);
}
else {
_strrev(p, src, dst+n-1);
_strrev2(src, p-1);
}
*(dst+n) = 0;
return dst;
}
int main()
{
char s[80];
char *src, *dst;
write(1, "s:", 2);
src = s+5;
gets(src);
printf("%s/n", strrev(src, src));
dst = s;
printf("%s/n", strrev(dst, src));
src = dst;
dst = s+10;
printf("%s/n", strrev(dst, src));
}
#include <stdlib.h>写一个atol
char *strstr(char *s, char *pattern)
{
char *p, *q;
char *pend, *ps;
int l;
if ( s==NULL||pattern==NULL)return s;
p = pattern; l = 0;
while ( *p != 0 ) ++p, ++l;
pend = p;
if ( pend == pattern )return s;
for ( ps = s; *ps != 0; ++ps )
{
p = ps; q = pattern;
while ( *q && (*q == *p) )p++,q++;
if ( *q == 0 ) return ps;
}
return NULL;
}
int main()
{
char s[80], p[80];
write(1, "s:", 2);
gets(s);
write(1, "p:", 2);
gets(p);
printf("%s/n", strstr(s, p));
return 0;
}
#include <stdlib.h>写一个不依赖库的strcpy
long myatol(char *s)
{
long r = 0;
while ( *s != 0 )
{
if ( *s >= '0' && *s <='9' )
r = r*10 + (*s-'0');
else return 0;
s++;
}
return r;
}
int main()
{
char s[80];
write(1, "s:", 2);
gets(s);
printf("%d", myatol(s));
}
#include <stdlib.h>
char *strcpy(char *dst, const char *src)
{
char *p;
if ( dst == NULL || src == NULL )
return NULL;
if ( dst == src ) return dst;
if ( dst < src ) {
p = dst;
while ( (*dst++ = *src++) );
return p;
}
else {
p = src; while ( *p++ ) ++dst;
while ( p != src ) *dst-- = *p--;
*dst = *p;
return dst;
}
}
int main()
{
char mem[]={0,0,0,0,0,
'h','e','l','l','o',',','w','o','r','l','d',0,
'x','x','x','x','x'};
char *dst1, *dst2, *src;
dst1 = mem;
dst2 = mem+10;
src = mem+5;
//printf("%s/n", strcpy(dst1, src));
printf("%s/n", src);
printf("%s/n", strcpy(dst2, src));
printf("%s/n", src);
}