版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qiaoermeng/article/details/88351167
关于字符串,首先输入的时候注意scanf和gets的区别:
gets函数可以一次接收一行输入串,其中可以有空格,也就是说空格可以做为字符串的一部分输入,而scanf函数接收的字符串不会含有空格,即遇到字空格时,认为字符串输入结束。
现在进入正题:
一,字符串的复制,其实可以直接用库函数strcpy()。但初学者建议自己写,有助于理解和进一步的学习。
下面附上代码:一个是指针一个是数组(不会指针的可以用数组的,但最好学一学指针,这里对于指针具体不多说,自己可以学习一下<( ̄▽ ̄)/)
下面是字符串复制代码:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
//void mystrcpy(char to[],char from[])//这个是数组方法
//{
// int i=0;
// while(from[i]!='\0')
// {
// to[i]=from[i];
// i++;
// }
// to[i]='\0';//结束标志
//}
void mystrcpy(char to[],char from[])//指针实现
{
int i=0;
//char *pt=to,pf=from;
while(*from!='\0')
{
*to=*from;
to++;
from++;
}
*to='\0';
}
int main()
{
char a[100],b[100];
printf("please print a string!: \n");
gets(b);//注意如果有空格不要用scanf
mystrcpy(a,b);
puts(a);
return 0;
}
二,在字符串的某个位置插入一个字符串。(最好用指针实现,不然有点麻烦。很适合初学者)
下面附上代码:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
void insert_string(char a[],char b[],int k,char ans[])
{
int i=0,lena=strlen(a),lenb=strlen(b),j=0;
for(i=0; i<k-1; i++)
{
*ans=*a;
a++;
ans++;
}
while(*b!='\0')
{
*ans=*b;
b++;
ans++;
}
while(*a!='\0')
{
*ans=*a;
a++;
ans++;
}
*ans='\0';
}
int main()
{
char a[100],b[100],ans[200];
int k;
gets(a);
gets(b);
scanf("%d",&k);
insert_string(a,b,k,ans);
puts(ans);
return 0;
}
注意:a,b,ans是数组名字,但是代表的是数组的第一个元素的地址。如有问题可以评论。代码已经调试,是正确的。