可以使用以下方法在C ++中进行字符串连接:
使用strcat()
标准库中的函数。
不使用标准库中的strcat()函数。
使用串联运算符。
在这里,我们使用strcat()
标准字符串库中的预定义函数。我们必须使用头文件<string.h>来实现此功能。
语法
char * strcat(char * destination, const char * source)
例
#include<iostream>
#include<string.h>
using namespace std;
int main(){
//字符串1-
char src[100]="Include help ";
//字符串2-
char des[100]="is best site";
//连接字符串
strcat(src, des);
//打印
cout<<src<<endl;
return 0;
}
输出结果
Include help is best site.
在这种情况下,我们不使用串联函数strcat()
来串联两个不同的字符串。
例
#include<iostream>
#include<string.h>
using namespace std;
int main(){
//声明字符串
char str1[100];
char str2[100];
//输入第一个字符串
cout<<"Enter first string : "<<endl;
cin.getline(str1,100);
//输入第二个字符串
cout<<"Enter second string : "<<endl;
cin.getline(str2,100);
//变量作为循环计数器
int i, j;
//保持第一个字符串不变
for(i=0; str1[i] != '\0'; i++)
{
;
}
//将字符串2的字符复制到字符串1-
for(j=0; str2[j] != '\0'; j++,i++)
{
str1[i]=str2[j];
}
//插入NULL-
str1[i]='\0';
//打印
cout<<str1<<endl;
return 0;
}