c语言连接两个字符串
2013-07-31 19:58
302 查看
第一种方法:
利用strcat()函数,这个就不多说了。
第二种方法
这种方法要s1的长度足够,不然肯定会越界
char s1[80],s2[40];
int i=0,j=0;
printf("\nInput the first string:");
scanf("%s",s1);
printf("\nInput the second string:");
scanf("%s",s2);
while (s1[i] !='\0')
i++;
while (s2[j] !='\0')
s1[i++]=s2[j++];
s1[i] ='\0';
printf("\nNew string: %s",s1);
第三种方法(利用返回指针的函数)
#include
#include
char *fun(char *s1,char *s2){
//一定要定义一个s指针指向s1,如果直接返回s1,那么结果就是空。
char *s=s1;
//这里一定不能写成while(*s1++!=0); 不然就只会输出s1的值
while(*s1!='\0')
s1++;
while(*s2!='\0')
*s1++=*s2++;
*s1='\0';
return s;
}
void main(){
char s1[100],s2[100];
printf("输入第一个字符串\n");
scanf("%s",&s1);
printf("输入第二个字符串\n");
scanf("%s",&s2);
printf("连接后的字符串:%s\n",fun(s1,s2));
//system("pause");
}
利用strcat()函数,这个就不多说了。
第二种方法
这种方法要s1的长度足够,不然肯定会越界
char s1[80],s2[40];
int i=0,j=0;
printf("\nInput the first string:");
scanf("%s",s1);
printf("\nInput the second string:");
scanf("%s",s2);
while (s1[i] !='\0')
i++;
while (s2[j] !='\0')
s1[i++]=s2[j++];
s1[i] ='\0';
printf("\nNew string: %s",s1);
第三种方法(利用返回指针的函数)
#include
#include
char *fun(char *s1,char *s2){
//一定要定义一个s指针指向s1,如果直接返回s1,那么结果就是空。
char *s=s1;
//这里一定不能写成while(*s1++!=0); 不然就只会输出s1的值
while(*s1!='\0')
s1++;
while(*s2!='\0')
*s1++=*s2++;
*s1='\0';
return s;
}
void main(){
char s1[100],s2[100];
printf("输入第一个字符串\n");
scanf("%s",&s1);
printf("输入第二个字符串\n");
scanf("%s",&s2);
printf("连接后的字符串:%s\n",fun(s1,s2));
//system("pause");
}
相关文章推荐
- c语言两个字符串数组的连接 通过地址搞定
- 将两个字符串连接。解决了c语言输入出现溢出现象
- 连接两个字符串 C语言
- C语言OJ项目参考(1052)两个字符串连接
- C语言 不使用strcat函数实现连接两个字符串功能
- 【c语言】将两个字符串连接起来,不要用strcat函数
- c语言连接两个字符串
- c语言中连接两个字符串
- (c语言)连接两个字符串
- C语言strcat()函数:连接字符串
- 将两个字符串连接起来取代第一个字符串。用string方法
- 第十三周项目5——将两个字符串连接仍保存到第一个字符串中
- C语言-字符串连接+字符串的复制
- 输入两个字符串,比如abdbcc和abc,输出第二个字符串在第一个字符串中的连接次序(递归方法)
- 第十五周 OJ 连接两个字符串
- 关于malloc动态连接两个字符串
- c语言:printf可以自动把两个字符串合并成一个字符串,并且可以合并多个
- 第十五周OJ(4)两个字符串连接
- C语言strcat()函数:连接字符串
- 利用C语言实现:输入两个字符串,统计一个字符串在另一个字符串中出现的次数 。