在C++开发中,字符串赋值是最常用的基础操作,由于C++存在C风格字符串和std::string两种主流字符串类型,不同类型的赋值方式存在明显区别,需要开发者根据使用场景选择合适的方法。

C风格字符串的赋值方法
C风格字符串本质是字符数组,不能直接使用赋值运算符进行整体赋值,需要通过特定函数或逐字符操作完成赋值。
1. 初始化时赋值
在定义字符数组时可以直接初始化赋值,这是最基础的C风格字符串赋值方式。
#include <iostream>
using namespace std;
int main() {
// 定义时直接初始化赋值
char str1[] = "hello world";
cout << str1 << endl;
return 0;
}
2. 使用strcpy函数赋值
对于已经定义的字符数组,需要使用<cstring>头文件中的strcpy函数完成赋值,该函数会将源字符串的内容复制到目标数组中,需要注意目标数组的空间要足够容纳源字符串。
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[20];
// 使用strcpy函数赋值
strcpy(str, "hello cpp");
cout << str << endl;
return 0;
}
3. 逐字符赋值
也可以通过循环遍历的方式逐字符给字符数组赋值,这种方式适合需要自定义赋值逻辑的场景。
#include <iostream>
using namespace std;
int main() {
char str[10];
// 逐字符赋值
str[0] = 'h';
str[1] = 'i';
str[2] = ' '; // 需要手动添加字符串结束符
cout << str << endl;
return 0;
}
std::string类型的赋值方法
std::string是C++标准库提供的字符串类型,封装了字符串的操作逻辑,赋值方式更加灵活便捷,不需要手动管理内存空间。
1. 直接赋值运算符赋值
std::string支持直接使用赋值运算符=进行赋值,既可以赋值为字符串字面量,也可以赋值为其他string对象。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1;
// 直接赋值为字符串字面量
s1 = "hello string";
string s2;
// 赋值为其他string对象
s2 = s1;
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
2. 构造函数赋值
在定义std::string对象时,可以通过构造函数直接完成赋值,支持多种构造参数。
#include <iostream>
#include <string>
using namespace std;
int main() {
// 用字符串字面量构造赋值
string s1("hello constructor");
// 用另一个string对象构造赋值
string s2(s1);
// 构造指定长度的重复字符
string s3(5, 'a');
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
return 0;
}
3. assign函数赋值
std::string提供了assign成员函数,支持更丰富的赋值逻辑,比如赋值指定长度的子串、重复字符等。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
// 赋值整个字符串
s.assign("hello assign");
cout << s << endl;
// 赋值字符串的前5个字符
s.assign("hello world", 5);
cout << s << endl;
// 赋值5个b字符
s.assign(5, 'b');
cout << s << endl;
return 0;
}
4. 从C风格字符串赋值
std::string可以直接接收C风格字符串进行赋值,也支持将自身内容转换为C风格字符串。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
char cstr[] = "c style string";
string s;
// 从C风格字符串赋值
s = cstr;
cout << s << endl;
// 转换为C风格字符串
const char* p = s.c_str();
cout << p << endl;
return 0;
}
两种字符串类型的赋值注意事项
- C风格字符串赋值必须保证目标数组空间足够,否则会导致缓冲区溢出,推荐使用strncpy函数限制复制长度,避免越界问题。
- std::string赋值不需要手动管理内存,会自动处理空间分配和释放,比C风格字符串更安全。
- 不能直接用赋值运算符给C风格字符数组整体赋值,这种写法在C++中是语法错误。
- 如果需要在两种字符串类型之间转换,std::string可以通过c_str()方法获取C风格字符串,C风格字符串可以直接赋值给std::string对象。
| 字符串类型 | 常用赋值方式 | 是否需要手动管理内存 |
|---|---|---|
| C风格字符串 | 初始化赋值、strcpy函数、逐字符赋值 | 是,需要保证数组空间足够 |
| std::string | 赋值运算符、构造函数、assign函数 | 否,自动管理内存 |