串连接
问题:字符串结尾记得加'\0';
发现自己代码写的真烂,逻辑太简单了。。。
代码:
#include <iostream> using namespace std; int main() { char *s1="hello"; char *s2="world"; char *c; char *c1; int len1,len2; len1=len2=0; c=s1; while(c[len1]!='\0') len1++; c=s2; while(c[len2]!='\0') len2++; c1=(char *)malloc((len1+len2+1)*sizeof(char)); int k=0,j=0; while(s1[k]!='\0') { c1[k]=s1[k]; k++; } while(s2[j]!='\0') { c1[k++]=s2[j]; j++; } c1[k]='\0'; cout<<c1<<endl; }
运行结果: