admin 管理员组

文章数量: 1184232


2024年1月18日发(作者:校园慕课网)

c语言 多个字符串拼接运算

在 C 语言中,你可以使用以下方法来拼接多个字符串:

1. 使用`+`运算符:

```c

#include

#include

int main() {

std::string str1 = "Hello";

std::string str2 = "World!";

std::string result = str1 + str2;

std::cout << "拼接后的字符串:" << result << std::endl;

return 0;

}

```

2. 使用`append()`成员函数:

```c

#include

#include

int main() {

std::string str1 = "Hello";

std::string str2 = "World!";

(str2);

std::cout << "拼接后的字符串:" << str1 << std::endl;

return 0;

}

```

3. 使用`+=`运算符:

```c

#include

#include

int main() {

std::string str1 = "Hello";

std::string str2 = "World!";

str1 += str2;

std::cout << "拼接后的字符串:" << str1 << std::endl;

return 0;

}

```

4. 使用`std::cout`和连续的`<<`运算符:

```c

#include

#include

int main() {

std::string str1 = "Hello";

std::string str2 = "World!";

std::cout << str1 << " " << str2 << std::endl;

return 0;

}

```

5. 使用`strcat()`函数:

```c

#include

#include

int main() {

char name[20] = "小明";

char aihao[30] = "喜欢钓鱼";

strcat(name, aihao);// 开始拼接

printf("%sn%s", name, aihao);// name 字符数组就会变成(小明喜欢钓鱼),

而 aihao 数组保持不变

return 0;

}

```

这些方法中的每一种都可以将两个或多个字符串拼接在一起。选择使用哪种方法取决于你的具体需求和代码结构。


本文标签: 拼接 字符串 使用 数组 方法