void main()
{
char s1[80] = "i am li 4,";
char*s2 ="and i am a student";
char *s3;
s3=concateString(s1,s2);
printf("the string after concate:%s\n",s3);
return:
}
我这里面是不是少了几句话
补充如下:
#include <stdio.h>
#include <stdlib.h>
char* concateString(const char* p1,const char* p2)
{
char* p = (char*)malloc(80);
char* pt = p;
while (*p1) { *p = *p1; p++; p1++; }
while (*p2) { *p = *p2; p++; p2++; }
*p = '\0';
return pt;
}
void main()
{
char s1[80] = "i am li 4,";
const char* s2 = "and i am a student";
char* s3;
s3 = concateString(s1, s2);
printf("the string after concate:%s\n", s3);
return;
}
return: 后面是分号。
concateString(s1,s2) 函数实现了没。
#include<stdio.h>//头文件
int main()//主函数
{
char str1[80],str2[40];//定义字符数组
int i=0,j=0;//定义整型变量且赋初值
printf("输入字符串1:");//提示语句
scanf("%s",str1); //录入字符串1
printf("输入字符串2:");//提示语句
scanf("%s",str2); //录入字符串2
while(str1[i]!='\0')//判断str1是不是最后一个字符
{
i++;
}
while(str2[j]!='\0')//判断str2是不是最后一个字符
{
str1[i++]=str2[j++];//逐个拼接
}
str1[i]='\0';
printf("\n新的字符串是:%s\n",str1);//输出拼接后的字符串
return 0;//主函数返回值为0
}
应该这样
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s1[80] = "i am li 4,";
char*s2 ="and i am a student";
char *s3;
s3=(char*)malloc(sizeof(char)*160);
int i=0,p=0;
while(s1[i]!='\0') s3[p++]=s1[i++];
i=0;
while(s2[i]!='\0') s3[p++]=s2[i++];
//s3=concateString(s1,s2);
printf("the string after concate:%s\n",s3);
return 0;
}
不浪费内存空间情况下,该连接函数能恰好容纳所需字串。 代码如下,仅供参考。谢谢!
#include<stdio.h>
#include<stdlib.h>
char* concateString(char *s1,char *s2);
int main()
{
char s1[80] = "i am li 4,";
char *s2 ="and i am a student";
char *s3;
s3=concateString(s1,s2);
printf("the string after concate:%s\n",s3);
//动态内存用完记得释放哦!
free(s3);
return 0;
}
//不浪费空间的情况下合理分配内存大小足够容纳所需
char* concateString(char *s1,char *s2)
{
char *p=(char*)malloc(1);
char *pstr;
int n=1;
int i=0,j=0;
while(*(s1+i)!='\0' && *(s1+i)!=EOF )
{
n++;
p=realloc(p,n);
*(p+i)=*(s1+i);
i++;
}
while(*(s2+j)!='\0' && *(s2+j)!=EOF )
{
n++;
p=realloc(p,n);
*(p+i+j)=*(s2+j);
j++;
}
*(p+i+j)='\0';
return p;
}