c++实现:编程实现两字符串的连接。要求使用string类定义字符串对象不能运用string类运算
可以使用字符数组和指针来实现字符串的连接。具体实现如下:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[20] = "hello";
char str2[20] = "world";
char *p = str1 + strlen(str1); // 指向str1的末尾
// 将str2拼接到str1的末尾
while (*str2 != '\0') {
*p++ = *str2++;
}
*p = '\0';
cout << str1 << endl;
return 0;
}
输出结果为:
helloworld
这里用到了指针的概念,p指向str1的末尾,*p表示p所指向的字符。通过循环将str2中的字符一个一个拷贝到str1的末尾,最后再在末尾加上结束符\0,就完成了字符串的拼接。
原文地址: https://www.cveoy.top/t/topic/8gn 著作权归作者所有。请勿转载和采集!