C++——string类

 


 
 

  ISO/ANSI C++98 标准通过添加 string 类扩展了 C++ 库,因此现在可以 string 类型的变量(使用 C++ 的话说是对象)而不是字符数组来存储字符串。string 类使用起来比数组简单,同时提供了将字符串作为一种数据类型的表示方法。
  要使用 string 类,必须在程序中包含头文件 string
  在很多方面,使用 string 对象的方式与使用字符数组相同。

  • 可以使用 C 风格字符串来初始化 string 对象。
  • 可以使用 cin 来将键盘输入存储到 string 对象中。
  • 可以使用 cout 来显示 string 对象。
  • 可以使用数组表示法来访问存储在 string 对象中的字符。

 
  string 类使得能够使用对象来表示字符串,并定义了赋值运算符、关系运算符和加法运算符(用于拼接)。另外,string 类还提供了自动内存管理功能,因此通常不用担心字符串被保存前,有人可能会跨越数组边界或将字符串截短。
  string 类提供了许多方便的方法。例如,可以将一个 string 对象追加到另一个对象的后面,也可以将 C 风格的字符串,甚至 char 值追加到 string 对象的后面。对于接受 C 风格字符串参数的函数,可以使用 c_str() 方法来返回一个适合的 char 指针。
  string 类不仅提供了一组设计良好的方法来处理与字符串相关的工作(如查找子字符串),而且与 STL 兼容,因此,可以将 STL 算法用于 string 对象。
 
 

 
 

 
 

构造

方法描述
string(const char *s)将 string 对象初始化为 s 指向的 NBTS
string(size_type n, char c)创建一个包含 n 个元素的 string 对象,其中每个元素都被初始化为字符 c
string(const string &str)将一个 string 对象初始化为 string 对象 str(复制构造函数)
string()创建一个默认的 string 对象,长度为 0(默认构造函数
string(const char *s, size_type n)将 string 对象初始化为 s 指向的 NBTS 的前 n 个字符,即使超过了 NBTS 结尾
template string(Iter begin, Iter end)将 string 对象初始化为区间 [begin,end) 内的字符,其中 begin 和 end 的行为就像指针,用于指定位置,范围包括 begin 在内,但不包括 end
string(const string &str, string size_type pos = 0, size_type n = npos)将一个 string 对象初始化为对象 str 中从位置 pos 开始到结尾的字符,或从位置 pos 开始的 n 个字符
string(string &&str) noexceptC++11 新增,它将一个 string 对象初始化为 string 对象 str,并可能修改 str(移动构造函数)
string(initializer_list il)C++11 新增,它将一个 string 对象初始化为初始化列表 il 中的字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1("qw1");//#case1
  cout << "1: " << str1 << endl;
  
  string str2(3, 'q');//#case2
  cout << "2: " << str2 << endl;
  
  string str3(str1);//#case3
  cout << "3: " << str3 << endl;
  
  string str4;//#case4
  str4 = str1 + str2;
  cout << "4: " << str4 << endl;
  
  char s5[] = "123456789";
  string str5(s5, 4);//#case5
  cout << "5: " << str5 << endl;
  
  string str6(s5 + 2, s5 + 6);//#case6 也可以用string str6(&s5[2], &s5[5]); 
  cout << "6: " << str6 << "\n";
  
  string str7(str4, 3, 1);//#case7 
  cout << "7: " << str7 << endl;
  string str8(str4, 3);//#case7
  cout << "8: " << str8 << endl;
  return 0;
}

运行结果
  构造函数 string(string &&str) 类似于复制构造函数,导致新创建的 string 为 str 的副本。但于复制构造函数不同的是,它不保证将 str 视为 const。
  构造函数 string(initializer_list il) 能够将列表初始化语法用于 string 类。如下所示是合法的:

string str1 = {'q', 'w', 'j', 'y'};
string str2 = {'1', '2', '3', '4'};

 
 

 
 

 
 

数据方法

方法返回值
begin()指向字符串第一个字符的迭代器
cbegin()一个 const_iterator,指向字符串中的第一个字符(C++11)
end()为超尾值的迭代器
cend()为超尾值得 const_interator(C++11)
rbegin()为超尾值的反转迭代器
crbegin()为超尾值的反转 const_interator(C++11)
rend()指向第一个字符的反转迭代器
crend()指向第一个字符的反转 const_interator(C++11)
size()字符串中的元素数,等于 begin() 到 end() 之间的距离
length()与 size() 相同
capacity()给字符串分配的元素数。这可能大于实际的字符数,capacity() - size() 的值表示在字符串末尾附加多少字符后需要分配更多的内存
max_size()字符串的最大长度
data()一个指向数组第一个元素的 const charT* 指针,其第一个 size() 元素等于 *this 控制的字符串中对应的元素,其下一个元素为 charT 类型的 char(0) 字符(字符串末尾标记)。当 string 对象本身被修改后,该指针可能无效
c_str()一个指向数组第一个元素的 const charT* 指针,其第一个 size() 元素等于 *this 控制的字符串中对应的元素,其下一个元素是 charT 类型的 char T(0) 字符(字符串尾标识)。当 string 对象本身被修改后,该指针可能无效
get_allocator()用于为字符串 object 分配内存的 allocator 对象的副本

 
 

内存方法描述
void resize(size_type n)如果 n>npos,将引发 out_of_range 异常;否则,将字符串的长度改为 n,如果 n<size(),则截短字符串,如果 n>size(),则使用 charT(0) 中的字符填充字符串
void resize(size_type n, charT c)如果 n>npos,将引发 out_of_range 异常;否则,将字符串的长度改为 n,如果 n<size(),则截短字符串,如果 n>size(),则使用字符 c 填充字符串
void reserve(size_type res_arg = 0)将 capacity() 设置为大于或等于 res_arg。由于这将重新分配字符串,因此以前的引用、迭代器和指针将无效
void shrink_to_fit()C++11新增,请求让 capacity() 的值与 size() 相同
void clear() noexcept删除字符串中所有字符
bool empty() const noexcept如果 size() == 0,则返回 0

 
 

 
 

 
 

字符串存取

数据方法描述
[ ] 运算符① reference operator [ ] (size_type pos);
第一个 operator [ ] 方法使得能够使用数组表示法来访问字符串的元素,可用于检索或更改值
② const_renference operator [ ] (size_type pos) const;
第二个 operator [ ] 方法可用于 const 对象,但只能用于检索值
at() 方法① reference at (size_type n);
② const_refference at (size_type n) const;
at() 方法提供了相似的访问功能,只是索引是通过函数参数提供的
substr() 方法basic_string substr(size_type pos = 0, size_type n = npos) const;
返回原始字符串的子字符串——从 pos 开始,复制 n 个字符(或到字符串尾部)得到的。
front() 方法C++11新增
front() 方法访问 string 的第一个元素,相当于 operator [ ] (0)
back() 方法C++11新增
brack() 方法访问 string 的最后一个元素,相当于 operator [ ] (size() - 1)
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1("qwjy");
	cout << str1[2] << endl;
	str1[1] = 'y';
	cout << str1 << endl;
	const string str2("qyjy");
	cout << str2[1] << "\n\n";
	
	cout << str1.at(1) << endl;
	cout << str2.at(1) << "\n\n";
	
	cout << str1.substr() << endl;//默认从0到size()复制
	cout << str1.substr(0) << endl;//默认复制size()个字符
	cout << str1.substr(0,2) << endl;//复制从0开始的2个字符 
	return 0;
} 

运行结果

  [ ] 运算符和 at() 方法差别在于(除语法差别外):at() 方法执行边界检查,如果 pos >= size(),将引发 out_of_range 异常。pos 的类型为 size_type,是无符号的,因此 pos 的值不能为负;而 operator [ ] ( ) 方法不进行边界检查,因此,如果 pos >= size(),则其行为将是不确定的(如果 pos == size(),const 版本将返回空值字符的等价物)。
  可以在安全性(使用 at() 检测异常)和执行速度(使用数组表示)之间进行选择。
 
 

 
 

 
 

赋值

方法描述
basic_string& operator=(const basic_string& str);将一个 string 对象赋值给另一个
string str("qw");
string str1 = str;
basic_string& operator=(const charT* s);将 C 风格字符串赋值给 string 对象
string str2 = "qw";
basic_string& operator=(charT c);将一个字符赋给 string 对象
string str3 = 'q';
basic_string& operator=(basic_string&& str) noexcept; //C++使用移动语义,将一个右值 string 对象赋给一个 string 对象
basic_string& operator=(initializer_list < charT >); //C++使用初始化列表进行赋值
string str5 = {'q', 'w', 'j', 'y'};
basic_string& assign(const basic_string& str);将一个string 对象 str 赋值给另一个
string str6;
str6.assign(str);
basic_string& assign(const basic_string& str, size_type pos, size_type n);将一个string 对象 str 的指定子串(从 pos 开始的 n 个字符)赋值给另一个
string str7;
str7.assign(str, 1, 1);
basic_string& assign(const charT* s);将 C 风格字符串 s 赋值给 string 对象
string str8;
str8.assign("qw");
basic_string& assign(const charT* s, size_type n);将 C 风格字符串 s 的指定子串(从 0 开始的 n 个字符)赋值给 string 对象
string str9;
str9.assign("qw", 1);
basic_string& assign(size_type n, charT c);将 n 个字符 c 赋值给 string 对象
string str10;
str10.assign(5, 'q');
basic_string& assign(initializer_list< charT >);使用初始化列表进行赋值
string str11;
str11.assign({'q', 'w', 'j', 'y'});

 
 

 
 

 
 

字符串搜索

find()

find() 函数原型描述
size_type find (const basic_string& str, size_type pos = 0) const noexcept;.返回 str 在调用对象中第一次出现时的起始位置。搜索从 pos 开始(默认为 0),如果没有找到子字符串,将返回 npos
string longer("QW is not very good, it is a waste.");
string shorter("good");
size_type loc1 = longer.find(shorter);
loc1 = longer.find(shorter, loc1 + 1);
size_type find (const charT* s, size_type pos = 0) const;完成同样的工作,但它使用字符数组而不是 string 对象作为子字符串
size_type loc2 = longer.find("QW");
size_type find (const charT* s, size_type pos, size_type n) const;完成同样的工作,但它只使用字符串 s 的前 n 个字符
size_type loc3 = longer.find("not", 2);
size_type find (charT c, size_type pos = 0) const noexcept;功能与第一个相同,但它使用一个字符而不是 string 对象作为子字符串
size_type loc5 = longer.find('a');
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("qw is not very good, qw's English is too bad.");
	string str1("qw"), str2("qy");
	cout << str.find(str1) << endl;//#1: 从默认下标0开始查找
	cout << str.find(str1, 1) << endl;//#1: 从指定下标1开始查找 
	cout << str.find(str2) << "\n\n";//#1: 没有找到 
	
	cout << str.find("qw") << endl;//#2:从默认下标0开始查找 
	cout << str.find("qw", 10) << "\n\n";//#2:从指定下标10开始查找 
	
	cout << str.find("qw", 1) << endl;//#3:从指定下标1开始查找 
	cout << str.find("qw", 1, 10) << "\n\n";//#3:从指定下标1至其后10个字符之间查找 
	
	cout << str.find('q') << endl;//#4:从默认下标0开始查找 
	cout << str.find('q', 1);//#4:从指定下标1开始查找 
	return 0;
} 

运行结果

 
 

rfind()

rfind() 函数原型描述
size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;返回 str 在调用对象中最后一次出现时的起始位置。搜索从 pos 开始(默认为 npos),如果没有找到子字符串,将返回 npos
size_type rfind(const charT* s, size_type pos = npos) const;完成同样的工作,但它使用字符数组而不是 string 对象作为子字符串
size_type rfind(const charT* s, size_type pos, size_type n) const;完成同样的工作,但它只使用字符串 s 的后 n 个字符
size_type rfind(charT c, size_type pos = npos) const noexcept;功能与第一个相同,但它使用一个字符而不是 string 对象作为子字符串
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("qw is not very good, qw's English is too bad.");
	string str1("qw"), str2("qy");
	cout << str.rfind(str1) << endl;//#1: 从默认下标npos开始向前查找
	cout << str.rfind(str1, 1) << endl;//#1: 从指定下标1开始向前查找 
	cout << str.rfind(str2) << "\n\n";//#1: 没有找到 
	
	cout << str.rfind("qw") << endl;//#2:从默认下标npos开始向前查找 
	cout << str.rfind("qw", 10) << "\n\n";//#2:从指定下标10开始向前查找 
	
	cout << str.rfind("qw", 1) << endl;//#3:从指定下标1开始向前查找 
	cout << str.rfind("qw", 25, 10) << "\n\n";//#3:从指定下标25至其前10个字符之间查找 
	
	cout << str.rfind('q') << endl;//#4:从默认下标npos开始向前查找 
	cout << str.rfind('q', 1);//#4:从指定下标1开始向前查找 
	return 0;
} 

运行结果

 
 

find_first_of()

find_first_of() 函数原型描述
size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;与对应 find() 方法的工作方法相似,但它们不是搜索整个子字符串,而是搜索子字符串中的字符首次出现的位置
size_type find_first_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_of(const charT* s, size_type pos = 0) const;
size_type find_first_of(charT c, size_type pos = 0) const noexcept;
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("qw is not very good, qw's English is too bad.");
	string str1("qw"), str2("not");
	//q是第一个在“qw”中的字符 
	cout << str.find_first_of(str1) << endl;//#1: 从默认下标0开始查找
	cout << str.find_first_of(str1, 1) << endl;//#1: 从指定下标1开始查找 
	cout << str.find_first_of(str2) << "\n\n";//#1: 从默认下标0开始查找
	
	cout << str.find_first_of("qw") << endl;//#2:从默认下标0开始查找 
	cout << str.find_first_of("qw", 10) << "\n\n";//#2:从指定下标10开始查找 
	
	cout << str.find_first_of("qw", 1) << endl;//#3:从指定下标1开始查找 
	cout << str.find_first_of("qw", 2, 10) << "\n\n";//#3:从指定下标2至其后10个字符之间查找 
	
	cout << str.find_first_of('q') << endl;//#4:从默认下标0开始查找 
	cout << str.find_first_of('q', 1);//#4:从指定下标1开始查找 
	return 0;
} 

运行结果

 
 

find_last_of()

find_last_of() 函数原型描述
size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept;与对应 rfind() 方法的工作方式相似,但它们不是搜索整个子字符串,而是搜索子字符串中出现的最后位置
size_type find_last_of(const charT* s, size_type pos, size_type n) const;
size_type find_last_of(const charT* s, size_type pos = npos) const;
size_type find_last_of(charT c, size_type pos = npos) const noexcept;
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("qw is not very good, qw's English is too bad.");
	string str1("qw"), str2("qy");
	//w是最后一个在“qw”中的字符 
	cout << str.find_last_of(str1) << endl;//#1: 从默认下标npos开始向前查找
	cout << str.find_last_of(str1, 1) << endl;//#1: 从指定下标1开始向前查找 
	cout << str.find_last_of(str2) << "\n\n";//#1: 从默认下标npos开始向前查找
	
	cout << str.find_last_of("qw") << endl;//#2:从默认下标npos开始向前查找 
	cout << str.find_last_of("qw", 10) << "\n\n";//#2:从指定下标10开始向前查找 
	
	cout << str.find_last_of("qw", 1) << endl;//#3:从指定下标1开始向前查找 
	cout << str.find_last_of("qw", 25, 10) << "\n\n";//#3:从指定下标25至其前10个字符之间查找 
	
	cout << str.find_last_of('q') << endl;//#4:从默认下标npos开始向前查找 
	cout << str.find_last_of('q', 1);//#4:从指定下标1开始向前查找 
	return 0;
} 

运行结果

 
 

find_first_not_of()

find_first_not_of() 函数原型描述
size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;与对应 find_first_of() 方法的工作方式相似,但它们搜索第一个不位于子字符串中的字符
size_type find_first_not_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_not_of(const charT* s, size_type pos = 0) const;
size_type find_first_not_of(charT c, size_type pos = 0) const noexcept;
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("qw is not very good, qw's English is too bad.");
	string str1("qw"), str2("qy");
	//空格是第一个没有在“qw”中出现的字符 
	cout << str.find_first_not_of(str1) << endl;//#1: 从默认下标0开始查找
	cout << str.find_first_not_of(str1, 1) << endl;//#1: 从指定下标1开始查找 
	//w是第一个没有在“qy”中出现的字符 
	cout << str.find_first_not_of(str2) << "\n\n";//#1: 从默认下标0开始查找
	
	cout << str.find_first_not_of("qw") << endl;//#2:从默认下标0开始查找 
	cout << str.find_first_not_of("qw", 10) << "\n\n";//#2:从指定下标10开始查找 
	
	cout << str.find_first_not_of("qw", 1) << endl;//#3:从指定下标1开始查找 
	cout << str.find_first_not_of("qw", 2, 10) << "\n\n";//#3:从指定下标2至其后10个字符之间查找 
	
	cout << str.find_first_not_of('q') << endl;//#4:从默认下标0开始查找 
	cout << str.find_first_not_of('q', 1);//#4:从指定下标1开始查找 
	return 0;
} 

运行结果

 
 

find_last_not_of()

find_last_not_of() 函数原型描述
size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept与对应 find_last_of() 方法的工作方式相似,但它们搜索的是最后一个没有在子字符串中的字符
size_type find_last_not_of(const charT* s, size_type pos, size_type n) const;
size_type find_last_not_of(const charT* s, size_type pos = npos) const;
size_type find_last_not_of(charT c, size_type pos = npos) const noexcept;
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str("qw is not very good, qw's English is too bad.");
	string str1("qw"), str2("qy");
	//.是最后一个没有出现在“qw”中的字符 
	cout << str.find_last_not_of(str1) << endl;//#1: 从默认下标npos开始向前查找
	cout << str.find_last_not_of(str1, 1) << endl;//#1: 从指定下标1开始向前查找 
	cout << str.find_last_not_of(str2) << "\n\n";//#1: 从默认下标npos开始向前查找
	
	cout << str.find_last_not_of("qw") << endl;//#2:从默认下标npos开始向前查找 
	cout << str.find_last_not_of("qw", 10) << "\n\n";//#2:从指定下标10开始向前查找 
	
	cout << str.find_last_not_of("qw", 1) << endl;//#3:从指定下标1开始向前查找 
	cout << str.find_last_not_of("qw", 25, 10) << "\n\n";//#3:从指定下标25至其前10个字符之间查找 
	
	cout << str.find_last_not_of('q') << endl;//#4:从默认下标npos开始向前查找 
	cout << str.find_last_not_of('q', 1);//#4:从指定下标1开始向前查找 
	return 0;
} 

运行结果

 
 

 
 

 
 

比较方法和函数

方法描述
int compare(const basic_string& str) const noexcept;①第一个字符串位于第二个字符串之前(小于),则返回一个小于 0 的值
②如果两个字符串相同,则它将返回 0
③如果第一个字符串位于第二个字符串后面(大于),则返回一个大于 0 的值
int compare(size_type pos1, size_type n1,
const basic_string& str) const;
与第一个方法相似,但它进行比较时,只使用第一个字符串中从位置 pos1 开始的 n1 个字符
int compare(size_type pos1, size_type n1,
const basic_string& str,
size_type pos2, size_type n2) const;
与第一个方法相似,但它使用第一个字符串中从 pos1 位置开始的 n1 个字符和第二个字符串中从 pos2 位置开始的 n2 个字符进行比较
int compare(const charT* s) const;与第一个方法相似,但它将一个字符数组而不是 string 对象作为第二个字符串
int compare(size_type pos1, size_type n1, const charT* s) const;与第三个方法相似,但它将一个字符数组而不是 string 对象作为第二个字符串
int compare(size_type pos1, size_type n1,
const charT* s, size_type n2) const;
与第三个方法相似,但它将一个字符数组而不是 string 对象作为第二个字符串
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1("abcdefg"), str2("abcdefg"), str3("bcdefg"), str4("bcdf");
	cout << str1.compare(str2) << endl;//#1: str1和str2相同,返回0 
	cout << str1.compare(str3) << endl;//#1: str1小于str3,返回-1 
	cout << str3.compare(str1) << "\n\n";//#1: str3大于str1,返回1 
	
	cout << str1.compare(1, 6, str3) << "\n\n";//#2: str1中下标1后6个字符的字串与str3比较——相同0 
	
	cout << str1.compare(1, 3, str4, 0, 3) << "\n\n";//#3: str1中下标1后3个字符的字串与str4中下标0后3个字符的子串比较——相同 0
	
	cout << str1.compare("abcdefg") << "\n\n";//#4: str1与“abcdefg”比较——相同 0
	
	cout << str1.compare(1, 3, "bcd") << "\n\n";//#5: str1中下标1后3个字符的子串与“bcd”比较——相同 0
	
	cout << str1.compare(1, 3, "bcdf", 3) << "\n";//#6: str1中下标1后3个字符的子串与“bcdf”中下标0后3个字符的子串比较——相同0
	cout << str1.compare(1, 3, "bcdf", 2) << "\n\n";//#6: str1中下标1后3个字符的子串与“bcdf”中下标0后2个字符的子串比较——大于1 
	return 0;
} 

运行结果
 
 
非成员比较函数是重载的关系运算符

运算符描述
operator == ()等于
operator < ()小于
operator <= ()小于等于
operator > ()大于
operator >= ()大于等于
operator != ()不等于
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1("abcdefg"), str2("abcdefg"), str3("bcdefg"), str4("bcdf");
	printf("%d\n", str1 == str2);
	printf("%d\n", str1 < str2);
	printf("%d\n", str1 <= str2);
	printf("%d\n", str1 > str2);
	printf("%d\n", str1 >= str2);
	printf("%d\n", str1 != str2);
	
	return 0;
} 

运行结果

 
 

 
 

 
 

字符串修改方法

追加和相加

  可以使用重载 += 运算符或 append() 方法将一个字符串追加到另一个字符串的后面。如果得到的字符串长于最大字符串长度。

+=运算符描述
basic_string& operator += (const basic_string& str);将 strinig 对象追加到 string 对象后面
basic_string& operator += (const charT* s);将字符串数组追加到 string 对象后面
basic_string& operator += (charT c);将单个字符追加到 string 对象后面

 
 

append() 方法原型描述
basic_string& append(const basic_string& str);在 string 字符串的末尾添加 string 对象 str
basic_string& append(const basic_string& str, size_type pos, size_type n);在 string 字符串的末尾添加 string 对象 str 的子串,子串以 pos 索引开始,长度为 n
basic_string& append(const charT* s);在 string 字符串的末尾添加字符数组 s
basic_string& append(const charT* s, size_type n);在 string 字符串的末尾添加 n 个字符数组 s
basic_string& append(size_type n, charT c);在 string 字符串的末尾添加 n 个字符 c
basic_string& append(InputIterator first, InputIterator last);在 string 字符串的末尾添加以迭代器 first 和 last 表示的字符序列
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1 = "qw is not very good";
	string str2 = ", qw's English is too bad.";
	string str3 = "Hi,";
	
	str1.append(str2);
	cout << str1 << endl;
	
	str3.append(str2, 2, 2);
	cout << str3 << endl;
	
	str2.append(6, '6');
	cout << str2 << endl;
	
	return 0;
} 

运行结果

 
 

其他方法描述
void push_back(charT c);将字符 c 添加到 string 字符串的末尾
operator + ()能够拼接字符串
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1 = "qw is not very good";
	str1.push_back('.');
	cout << str1 << endl;
	
	string str2 = str1 + ", qw's English is too bad.";
	cout << str2 << endl;
	string str3 = str2 + str1;
	cout << str3 << endl;
	return 0;
} 

运行结果

 
 

插入方法

方法描述
basic_string& insert(size_type pos1, const basic_string& str);在 pos1 位置插入一个 string 对象 str
basic_string& insert(size_type pos1, const basic_string& str, size_type pos2, size_type n);在 pos1 位置插入一个 string 对象的子串(从 pos2 开始的 n 个字符)
basic_string& insert(size_type pos, const charT* s);在 pos 位置插入一个常量字符串
basic_string& insert(size_type pos, const charT* s, size_type n);在 pos 位置插入常量字符串的一个子串(从 0 开始的 n 个字符)
basic_string& insert(size_type pos, size_type n, charT c);在 pos 位置插入 n 个字符 c
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1 = "qy";
	string str2 = "wj";
	str1.insert(1, str2);
	cout << str1 << endl;
	
	string str3 = "qwjy";
	str1 = "qy";
	str1.insert(1, str3, 1, 2);
	cout << str1 << endl;
	
	string str4 = "w";
	str4.insert(0, "q");
	cout << str4 << endl;
	
	string str5 = "w";
	str5.insert(0, "qwqwqw", 1);
	cout << str5 << endl;
	
	string str6 = "w";
	str6.insert(0, 6, 'q');
	cout << str6 << endl;
	return 0;
} 

运行结果

 
 

清除方法

方法描述
basic_string& erase(size_type pos = 0, size_type n = npos);从 pos 位置开始,删除 n 个字符或删除到字符串尾
iterator erase(const_iterator position);删除迭代器位置引用的字符,并返回指向下一个元素的迭代器;如果后面没有其他元素,则返回 end()
iterator erase(const_iterator first, iterator last);删除区间 [first, last) 中的字符,即从 first(包括)到 last(不包括)之间的字符;返回最后一个迭代器,该迭代器指向最后一个被删除的元素后面的一个元素
void pop_back();删除字符串中的最后一个字符
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1 = "qw is not very good";
	str1.erase(0, 3);
	cout << str1 << endl;
	
	str1.pop_back();
	cout << str1 << endl;
	return 0;
} 

运行结果

 
 

替换方法

方法描述
basic_string& replace (size_type pos1, size_type n1, const basic_string& str);用 str 替换指定字符串从起始位置 pos1 开始长度为 n 的字符
basic_string& replace (size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2);用 str 的指定子串(给定起始位置 pos2 和长度 n2)替换从指定位置上的字符串(从起始位置 pos1 开始长度为 n 的字符)
basic_string& replace (size_type pos, size_type n1, const charT* s);用字符数组 str 替换从起始位置 pos1 开始长度为 n 的字符
basic_string& replace (size_type pos, size_type n1, const charT* s, size_type n2);用字符数组 str 指定位置(从起始位置 0 开始长度为 n2 的子串)替换从起始位置 pos1 开始长度为 n 的字符
basic_string& replace (size_type pos, size_type n1, size_type n2, charT c);用重复 n2 次的 c 字符替换从指定位置pos 长度为 n1 的字符
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1 = "qy";
	string str2 = "w";
	str1.replace(1, 1, str2);
	cout << str1 << endl;
	
	string str3 = "qwjy";
	str1 = "qy";
	str1.replace(1, 1, str3, 1, 3);
	cout << str1 << endl;
	
	string str4 = "w";
	str4.replace(0, 1, "q");
	cout << str4 << endl;
	
	string str5 = "w";
	str5.replace(0, 1, "qwqwqw", 2);
	cout << str5 << endl;
	
	string str6 = "qqqqw";
	str6.replace(0, 4, 1, 'q');
	cout << str6 << endl;
	return 0;
} 

运行结果

 
 

其他方法

其他方法描述
size_type copy(charT* s, size_type n, size_type pos = 0) const;将 string 对象或其中一部分复制到指定的字符串数组中。其中,s 指向目标数组,n 是要复制的字符数,pos 指出从 string 对象的什么位置开始复制。注意长度是否足够。
void swap(basic_string& str);使用一个时间恒定的算法来交换两个 string 对象
#include<iostream>
#include<string>
using namespace std;
int main(){
	string str1 = "qw is not very good";
	string str2 = "qw's English is too bad.";
	char str3[60];
	str1.copy(str3, 30);
	cout << str3 << endl;
	char str4[60];
	str2.copy(str4, 7, 5);
	printf("%s\n", str4);
	
	str1.swap(str2);
	cout << str1 << endl;
	cout << str2 << endl;
	return 0;
} 

运行结果

 
 

 
 

 
 

输出与输入

方法描述
<< 和 >><<” 和 “>>” 提供了 C++ 语言的字符串输入和字符串输出功能,到达文件尾、读取字符串允许的最大字符数或遇到空白字符后,输入将终止
getline()getline() 从输入中读取字符,可以设置分界符(不设置,默认为“\n”)
c_str()用转换函数c_str(),该函数将 string 类型的变量转换为一个 const 的字符串数组的指针

<<” 和 “>>” 提供了 C++ 语言的字符串输入和字符串输出功能。

#include <iostream>
using namespace std;
int main()
{
  string str;
  cin >> str;//将输入读入到字符串 
  cout << str << endl;//输出 
  return 0;
}

运行结果
  到达文件尾、读取字符串允许的最大字符数或遇到空白字符后,输入将终止(空白的定义取决于字符集以及 charT 表示的类型)。

还有一个常用的 getline() 函数,该函数的原型包括两种形式:

template <class CharT, class traits, class Allocator > basic_istream<CharT, traits>& getline (basic_istream<CharT, traits>& is, basic_string <CharT,traits, Allocator> & str);
//上述原型包含 2 个参数:第 1 个参数是输入流;第 2 个参数是保存输入内容的字符串
template <class CharT, class traits, class Allocator > basic_istream<CharT, traits>& getline (basic_istream<CharT, traits>& is, basic_string <CharT,traits, Allocator> & str, charT delim);
//上述原型包含 3 个参数:第 1 个参数是输入流,第 2 个参数保存输入的字符串,第 3 个参数指定分界符。

  这个函数将输入流 is 中的字符读入到字符串 str 中,直到遇到定界字符 delim、到达文件尾或者到达字符串的最大长度。delim 字符将被读取(从输入流中删除),但不被存储。

#include <iostream>
using namespace std;
int main()
{
  string str1, str2;
  getline(cin, str1);
  getline(cin, str2, '.');//以“.”为分界符 
  cout << "str1: " << str1 << endl;
  cout << "str2: " << str2 << endl;
  return 0;
}

运行截图

也可以用转换函数c_str(),该函数将 string 类型的变量转换为一个 const 的字符串数组的指针。

#include <iostream>
using namespace std;
int main()
{
  string str;
  getline(cin, str);
  printf("%s", str.c_str()) ;
  return 0;
}

运行结果

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的C++文字RPG游戏的示例代码,其中包括了基本的角色、战斗和物品系统: ```c++ #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; // 角色 class Character { public: string name; int hp; int atk; int def; int gold; Character(string n, int h, int a, int d, int g) { name = n; hp = h; atk = a; def = d; gold = g; } // 攻击函数 void attack(Character& other) { int damage = atk - other.def; if (damage < 0) { damage = 0; } other.hp -= damage; cout << name << "攻击了" << other.name << ",造成了" << damage << "点伤害。" << endl; } // 是否死亡 bool isDead() { return hp <= 0; } }; // 物品 class Item { public: string name; int price; int hp; int atk; int def; Item(string n, int p, int h, int a, int d) { name = n; price = p; hp = h; atk = a; def = d; } }; // 商店 class Shop { public: Item items[3]; Shop() { items[0] = Item("草药", 10, 20, 0, 0); items[1] = Item("铁剑", 50, 0, 10, 0); items[2] = Item("铁甲", 100, 0, 0, 10); } // 显示商店物品 void showItems() { cout << "欢迎光临!以下是本店的物品:" << endl; for (int i = 0; i < 3; i++) { cout << i + 1 << ". " << items[i].name << " - " << items[i].price << "金币" << endl; } } // 购买物品 bool buy(Character& c, int choice) { if (c.gold < items[choice - 1].price) { cout << "金币不足,法购买!" << endl; return false; } c.gold -= items[choice - 1].price; c.hp += items[choice - 1].hp; c.atk += items[choice - 1].atk; c.def += items[choice - 1].def; cout << "购买成功!" << endl; return true; } }; // 战斗函数 void battle(Character& player, Character& enemy) { cout << "你遇到了一只" << enemy.name << ",准备战斗!" << endl; while (!player.isDead() && !enemy.isDead()) { player.attack(enemy); if (enemy.isDead()) { cout << enemy.name << "被你打败了!" << endl; player.gold += enemy.gold; return; } enemy.attack(player); if (player.isDead()) { cout << "你被" << enemy.name << "打败了!" << endl; return; } } } int main() { srand(time(NULL)); // 初始化随机数种子 // 初始化角色和商店 Character player("勇者", 100, 10, 5, 50); Character enemies[3] = { Character("史莱姆", 30, 5, 2, 10), Character("骷髅兵", 50, 10, 5, 20), Character("巨龙", 100, 20, 10, 50) }; Shop shop; // 游戏循环 while (true) { cout << "你的状态 - HP:" << player.hp << " ATK:" << player.atk << " DEF:" << player.def << " 金币:" << player.gold << endl; cout << "请选择操作:" << endl; cout << "1. 进入商店" << endl; cout << "2. 进行战斗" << endl; cout << "3. 离开游戏" << endl; int choice; cin >> choice; switch (choice) { case 1: shop.showItems(); cout << "请选择要购买的物品(输入编号):" << endl; cin >> choice; shop.buy(player, choice); break; case 2: battle(player, enemies[rand() % 3]); break; case 3: cout << "游戏结束,欢迎再次光临!" << endl; return 0; default: cout << "无效的操作!" << endl; break; } } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值