c++ string 赋值
时间: 2025-02-14 17:18:41 浏览: 164
### C++ 中字符串赋值方法
在 C++ 中,`std::string` 提供了多种方式来进行字符串的赋值操作。以下是几种常见的字符串赋值方法:
#### 使用构造函数初始化
可以直接通过构造函数来创建并初始化 `std::string` 对象。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1("Hello");
std::string str2 = "World";
std::cout << str1 << ' ' << str2 << std::endl;
}
```
#### 赋值运算符 (=)
可以使用简单的赋值语句给已存在的 `std::string` 变量赋予新值[^1]。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str;
str = "Hello"; // Assigning a literal string
std::cout << str << std::endl;
}
```
#### assign 方法
除了普通的赋值外,还可以调用成员函数 `assign()` 来完成更复杂的赋值逻辑,比如指定范围内的字符复制等。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str;
str.assign("Hello, world!", 6); // Copy first six characters only
std::cout << str << std::endl;
}
```
#### append 或者 += 运算符追加数据
当需要向现有字符串后面添加更多内容时,可采用 `append()` 函数或是 `+=` 操作符。
```cpp
#include <iostream>
#include <string>
int main() {
std::string greeting = "Good morning!";
greeting.append(", everyone"); // Using append method
std::string message = "Welcome ";
message += "to our community."; // Using += operator
std::cout << greeting << '\n' << message << std::endl;
}
```
这些就是一些常用的 C++ 字符串赋值的方式,在实际编程过程中可以根据具体需求选择合适的方法。
阅读全文
相关推荐


















