在C++中,
赋值(assign) 使用 插入(insert) 使用 删除(erase) 使用 替换(replace) 使用 交换(swap) 使用 附加(append) 使用 清空(clear) 使用 这些只是 std::string 是一个非常重要的类,它位于 头文件中。std::string` 提供了许多用于修改字符串的成员函数。以下是一些常用的修改操作:
assign() 函数可以为字符串赋新值。例如:std::string str = "Hello";
str.assign("World"); // str 现在是 "World"
insert() 函数可以在字符串的指定位置插入字符或子字符串。例如:std::string str = "Hello";
str.insert(5, " World"); // str 现在是 "Hello World"
erase() 函数可以从字符串中删除指定位置的字符或子字符串。例如:std::string str = "Hello World";
str.erase(5, 6); // str 现在是 "Hello"
replace() 函数可以替换字符串中的指定子字符串。例如:std::string str = "Hello World";
str.replace(6, 5, "C++"); // str 现在是 "Hello C++"
swap() 函数可以交换两个字符串的内容。例如:std::string str1 = "Hello";
std::string str2 = "World";
str1.swap(str2); // str1 现在是 "World",str2 现在是 "Hello"
append() 函数可以在字符串末尾添加字符或子字符串。例如:std::string str = "Hello";
str.append(" World"); // str 现在是 "Hello World"
clear() 函数可以清空字符串的内容。例如:std::string str = "Hello World";
str.clear(); // str 现在是空字符串 ""
std::string 类提供的一些修改操作。还有其他一些函数,如 operator[]、at()、front()、back() 等,可以用于访问和修改字符串中的单个字符。请注意,这些操作可能会导致字符串的长度发生变化。