5.不调用库函数,用C语言实现字符串复制(strcpy函数)。
#include<stdio.h>
#include<assert.h>
void my_strcpy(char *strdest, const char *strsrc);
int main(void)
{
char src[32],dest[32];
printf("please input src_string:\n");
scanf("%s",src);
printf("the src_string is :%s\n",src);
my_strcpy(dest, src);
printf("the string after of copy is : %s\n",dest);
return 0;
}
void my_strcpy(char *strdest, const char *strsrc)
{
assert((strdest != NULL)&&(strsrc != NULL));
while((*strdest++ = *strsrc++)!='\0');
NULL;
}
拷贝函数的标准写法如下:
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include<string.h>
void my_strcpy(char *strdest, const char *strsrc);
int main(void)
{
char *a ,*b;
a = (char *)malloc(20);
b = (char *)malloc(20);
my_strcpy(a,"akjfkajl");
my_strcpy(b,a);
printf("the a is : %s\n",a);
printf("the b is : %s\n",b);
return 0;
}
void my_strcpy(char *strdest, const char *strsrc)
{
assert((strdest != NULL)&&(strsrc != NULL));
while(*strsrc != '\0')
{
*strdest++ = *strsrc++;
}
*strdest = '\0';
}
6.编写一个函数,作用是把一个char组成的字符串循环右移n个。
方法一:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Loopmov(char *pstr, int steps);
int main(void)
{
char str[50];
int n;
scanf("%s",str);
printf("the grapheme before mov is : %s\n",str);
scanf("%d",&n);
printf("the mov steps is: %d\n",n);
Loopmov(str, n);
return 0;
}
void Loopmov(char *pstr, int steps)
{
int n = strlen(pstr) - steps;
char temp[100];
strcpy(temp,pstr+n);
strcpy(temp+steps,pstr);
*(temp + strlen(pstr)) = '\0';
strcpy(pstr,temp);
printf("the grapheme after mov is : %s\n",pstr);
}
方法二:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Loopmov(char *pstr, char *steps);
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("please input three arguments !\n");
exit(1);
}
Loopmov(argv[1], argv[2]);
return 0;
}
void Loopmov(char *pstr, char *steps)
{
int a = atoi(steps);
int n = strlen(pstr) - a;
char temp[100];
strcpy(temp,pstr+n);
strcpy(temp+a,pstr);
*(temp + strlen(pstr)) = '\0';
strcpy(pstr,temp);
printf("the grapheme after mov is : %s\n",pstr);
}
方法三:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Loopmov(char *pstr, char *steps);
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("please input three arguments !\n");
exit(1);
}
Loopmov(argv[1], argv[2]);
return 0;
}
void Loopmov(char *pstr, char *steps)
{
int a = atoi(steps);
int n = strlen(pstr) - a;
char temp[100];
memcpy(temp,pstr+n,a);
memcpy(pstr+a,pstr,n);
memcpy(pstr,temp,a);
printf("the grapheme after mov is : %s\n",pstr);
}
注:void *memcpy(void *dest,const void *src,size_t n);
复制src所指向的内存前n个字节到dest 所指向的内存,返回dest的值。