温馨提示×

c++中string字符串赋值的方法是什么

小亿
105
2023-11-03 02:59:26
栏目: 编程语言

在C++中,可以使用以下方法对string字符串进行赋值:

  1. 使用赋值运算符(=):
std::string str1;
std::string str2 = "Hello";
str1 = str2; // 将str1赋值为str2的内容
  1. 使用assign()函数:
std::string str1;
std::string str2 = "Hello";
str1.assign(str2); // 将str1赋值为str2的内容
  1. 使用字符串字面值进行赋值:
std::string str1;
str1 = "Hello"; // 将str1赋值为字符串字面值"Hello"
  1. 使用字符数组进行赋值:
std::string str1;
char arr[] = "Hello";
str1 = arr; // 将str1赋值为字符数组的内容
  1. 使用字符串的子串进行赋值:
std::string str1 = "Hello, World!";
std::string str2;
str2 = str1.substr(7, 5); // 将str2赋值为str1从索引位置7开始,长度为5的子串 "World"

0