/* 实现库函数strmcpy、strmcat和strmcmp,它们最多对变元字符串的前 m个字符进行
操作。例如,函数strmcpy(s, t, m)将t所指向字符串中最多前m个字符复制到s所指向的字符数组中。 */
#include <stdio.h>
/* strmcpy:将字符串t中的前m个字符复制到字符串s中 */
void strmcpy( char *s , char *t , int m ){
char *a = s;
char *b = t;//记录指针s,t的初始位置
for (s = a , t = b ; t <= b + m ; t++,s++){//将指针从初始位置后移,直到移动n个字符
*s = *t;
}
}
/* strmcat:将字符串t中的前m个字符接到字符串s后面 */
void strmcat ( char *s , char* t ,int m){
char *a = s;
char *b = t;//记录指针s,t的初始位置
while ( *s )
s++; //找到s的结束位置
for ( t = b ; t <= b+m ; s++, t++){//将t指向的字符接到s后面,直到t移动从初始位置移动够m个字符
*s = *t;
}
}
/* strmcmp:将字符串t中的前m个字符接和s中的前m个字符进行比较 */
int strmcmp ( char* s , char *t , int m){
char *a = s;
char *b = t;//记录指针s,t的初始位置
while ( s < a+m && t < b+m ){
if ( *s != *t ){
return *s - *t ;
}
s++;
t++;
}
return 0;
}
int main()
{
char a[30] = "abc";
char b[20] = "abe";
char *s = a;
char *t = b;
int m = 2 ;
strmcpy ( s , t , m );
printf("%s\n",s);
strmcat ( s , t , m);
printf("%s\n", s);
if ( strmcmp(s , t , m ) > 0)
printf("s > t");
else if (strmcmp(s , t , m ) < 0)
printf("s < t");
else printf(" s = t ");
return 0;
}
练习5-5 实现库函数s t r n c p y、s t r n c a t和s t r n c m p,它们最多对变元字符串的前 n个字符进行 操作。例如,函数strncpy(s, t, n)将t所
猜你喜欢
转载自blog.csdn.net/weixin_44127727/article/details/88355503
今日推荐
周排行