编程实现两个字符串的连接
时间: 2023-09-26 08:13:54 浏览: 49
在大多数编程语言中,可以使用加号或连接函数来实现两个字符串的连接。以下是几个示例:
在 Python 中,可以使用加号操作符:
```python
str1 = "Hello"
str2 = "world"
result = str1 + str2
print(result)
```
输出:
```
Helloworld
```
在 Java 中,可以使用加号操作符或 `concat()` 方法:
```java
String str1 = "Hello";
String str2 = "world";
String result = str1 + str2;
System.out.println(result);
// 或者使用 concat() 方法
String result2 = str1.concat(str2);
System.out.println(result2);
```
输出:
```
Helloworld
Helloworld
```
在 JavaScript 中,可以使用加号操作符或 `concat()` 方法:
```javascript
var str1 = "Hello";
var str2 = "world";
var result = str1 + str2;
console.log(result);
// 或者使用 concat() 方法
var result2 = str1.concat(str2);
console.log(result2);
```
输出:
```
Helloworld
Helloworld
```
在 C++ 中,可以使用加号操作符或 `append()` 方法:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "world";
string result = str1 + str2;
cout << result << endl;
// 或者使用 append() 方法
string result2 = str1.append(str2);
cout << result2 << endl;
return 0;
}
```
输出:
```
Helloworld
Helloworld
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)