【String的介绍及使用】

String的介绍及使用

##

小杨

为何学习string以及string的简单介绍

学习string类的原因

C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,
但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可
能还会越界访问。

简单介绍string类
  1. 字符串是表示字符序列的类
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作
    单字节字符字符串的设计特性。
  3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型。
  4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits
    和allocator作为basic_string的默认参数。
  5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个
    类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

  1. string是表示字符串的字符串类

  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。

  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;

  4. 不能操作多字节或者变长字符的序列。 在使用string类时,必须包含#include头文件以及using namespace std;

函数的定义

功能简单概括函数名称功能说明
defaultstring()构造空的string对象,即空字符串
copystring(const string& str)拷贝构造str对象
substringstring(const string& str, size_t pos, size_t len = npos)从str的pos位置开始复制len个字符
from c - stringstring(const char* s)用C-string来构造string类对象
from sequencestring(const char* s, size_t n)复制指向s的前n个字符
fillstring(size_t n, char c)复制n个c字符
rangetemplate string(InputIterator first, InputIterator last)迭代器区间构造
	string();//构造空字符串

	string str1("嗨嗨,来喽!");
	string str2(str1);//拷贝构造

	string str3(str1, 0, 3);//从str1的第0个位置开始复制3个字符

	string str4("我是C风格的字符串");//C-string来构造string对象

	string str5("我是C风格的字符串", 3);//复制C-stirng的前3个字符

	string str6(10, 'c');//复制10个字符c


	vector<char> v1{ 'a','v','b','c'};
	string str7(v1.begin(), v1.end());//迭代器区间构造
	while (!str7.empty())
	{
		cout << str7 << "";
		str7.erase();
	}

赋值运算符

string& operator= (const string& str);

string& operator= (const char* s);

string& operator= (char c);

  std::string str1, str2, str3;
  str1 = "Test string: ";   // c-string
  str2 = 'x';               // single character
  str3 = str1 + str2;       // string

  std::cout << str3  << '\n';
//answer
Test string: x

迭代器相关

begin和end

Returns/ an iterator /pointing/ to the first character/ of the string.
返回一个指向字符串第一个位置的迭代器

iterator begin(); 
const_iterator begin() const;

Returns/ an iterator/ pointing /to the past-the-end character /of the string.
返回一个指向字符串末尾后的迭代器

  iterator end();
  const_iterator end() const;
	string s1("这是最好的时代,这是最坏的时代");
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it;
		++it;
	}

	std::string str("test string");
	for (std::string::iterator it = str.begin(); it != str.end(); ++it)
		std::cout << *it<<" ";


		std::cout << '\n';

在这里插入图片描述

rbegin和rend

Returns/ a reverse iterator/ pointing /to the last character /of the string
返回一个指向字符串最后一个字符的反向迭代器

  reverse_iterator rbegin();
  const_reverse_iterator rbegin() const;

Returns/ a reverse iterator/ pointing/ to the theoretical element /preceding the first character/ of the string (which is considered its reverse end).
返回一个反向迭代器,指向字符串第一个字符前面的理论元素(被认为是字符串的反向结束)。

	string s1("abcdefg");
	string::reverse_iterator it = s1.rbegin();
	while (it != s1.rend())
	{
		cout << *it;
		++it;
	}

在这里插入图片描述

容量相关

size和length

size_t size() const;
size_t length() const;

两者都是返回字符串的长度,只是名字不同。

string s1("hello");
cout << s1.size() << " " << s1.length() << endl;

在这里插入图片描述

max_size

size_t max_size() const;

返回字符串的最大大小

std::string str("Test string");
std::cout << "size: " << str.size() << "\n";
std::cout << "length: " << str.length() << "\n";
std::cout << "capacity: " << str.capacity() << "\n";
std::cout << "max_size: " << str.max_size() << "\n";

在这里插入图片描述

resize

void resize (size_t n);
void resize (size_t n, char c);

改变字符串大小

void resize (size_t n);
void resize (size_t n, char c);//多余的用给定的c字符代替

如果n小于当前字符串,就将当前长度缩短到n个字符,移除多余的字符。
如果n大于当前字符串长度,当前字符填充到n,如果n被制定了,就用那个指定了的字符插入。

	std::string str("I like to code in C");
	std::cout << str << '\n';

	unsigned sz = str.size();

	str.resize(sz + 2, '+');
	std::cout << str << '\n';

	str.resize(14);
	std::cout << str << '\n';

在这里插入图片描述

capacity

size_t capacity() const;

返回当前字符串所开辟的空间

	std::string str("Test string");
	std::cout << "size: " << str.size() << "\n";
	std::cout << "length: " << str.length() << "\n";
	std::cout << "capacity: " << str.capacity() << "\n";
	std::cout << "max_size: " << str.max_size() << "\n";

在这里插入图片描述

reserve

void reserve (size_t n = 0);

请求容量的改变
 1、当n大于对象当前的capacity时,将capacity扩大到n或大于n。
 2、当n小于对象当前的capacity时,什么也不做。

		string s("YZH");
		cout << s << endl; //YZH
		cout << s.size() << endl; //3
		cout << s.capacity() << endl; //15

		//reverse(n)当n大于对象当前的capacity时,将当前对象的capacity扩大为n或大于n
		s.reserve(100);
		cout << s << endl; //YZH
		cout << s.size() << endl; //3
		cout << s.capacity() << endl; //111

		//reverse(n)当n小于对象当前的capacity时,什么也不做
		s.reserve(1);
		cout << s << endl; //YZH
		cout << s.size() << endl; //3
		cout << s.capacity() << endl; //111
clear

void clear();

清空字符串

	string s1("hello");
	s1.clear();
	cout << s1 << endl;//空
empty

bool empty() const;

检测字符串是否为空

	string s1("hello");
	//如果返回1即为空,否则不为空
	cout << s1.empty() << endl;

在这里插入图片描述

元素访问相关

operator[ ]
  char& operator[] (size_t pos); 
  const char& operator[] (size_t pos) const;

Returns/ a reference/ to the character/ at position pos/ in the string.
返回对字符串中位置为pos的字符的引用。

	std::string str("Test string");
	str[0]='y';
	for (int i = 0; i < str.length(); ++i)
	{
		std::cout << str[i];//访问指定元素下标  yest string
	}
at
  char& at (size_t pos); 
  const char& at (size_t pos) const;

Returns/ a reference/ to the character/ at position pos/ in the string.
返回对字符串中位置为pos的字符的引用。

	std::string str("Test string");
	for (int i = 0; i < str.length(); ++i)
	{
		std::cout << str.at(i);
	}

string修改相关

operator+=

string (1) string& operator+= (const string& str);
c-string (2) string& operator+= (const char* s);
character (3) string& operator+=(char c);

Extends the string by appending additional characters at the end of its current value:
在当前字符串的末尾追加

	std::string name("John");
	std::string family("Smith");
	name += " K. ";         // c-string
	name += family;         // string
	name += '\n';           // character
append
函数声明函数解释
string& append (const string& str);追加字符串
string& append (const string& str, size_t subpos, size_t sublen);追加子串
string& append (const char* s);追加C风格字符串
string& append (const char* s, size_t n);追加字符串的前n个字符
string& append (size_t n, char c);追加n个c字符
template string& append (InputIterator first, InputIterator last);迭代器追加
  std::string str;
  std::string str2="Writing ";
  std::string str3="print 10 and then 5 more";

  // used in the same order as described above:
  str.append(str2);                       // "Writing "
  str.append(str3,6,3);                   // "10 "
  str.append("dots are cool",5);          // "dots "
  str.append("here: ");                   // "here: "
  str.append(10u,'.');                    // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append<int>(5,0x2E);                // "....."

  std::cout << str << '\n';
push_back

void push_back (char c);
将字符c追加到字符串的末尾,使其长度增加1。

	string s1("hello");
	cout << s1.size() << endl;
	s1.push_back('y');
	cout << s1 << " " << s1.size();

在这里插入图片描述

assign
Column 1Column 2
string& assign (const string& str);用str替换当前字符串
string& assign (const string& str, size_t subpos, size_t sublen);子串替换
string& assign (const char* s);C风格字符串替换
string& assign (const char* s, size_t n);用s的前n个字符替换
string& assign (size_t n, char c);用n个c来替换
template string& assign (InputIterator first, InputIterator last);用迭代器区间替换

为字符串赋一个新值,替换其当前内容。

std::string str;
  std::string base="The quick brown fox jumps over a lazy dog.";

  // used in the same order as described above:

  str.assign(base);
  std::cout << str << '\n';

  str.assign(base,10,9);
  std::cout << str << '\n';         // "brown fox"

  str.assign("pangrams are cool",7);
  std::cout << str << '\n';         // "pangram"

  str.assign("c-string");
  std::cout << str << '\n';         // "c-string"

  str.assign(10,'*');
  std::cout << str << '\n';         // "**********"

  str.assign<int>(10,0x2D);
  std::cout << str << '\n';         // "----------"

  str.assign(base.begin()+16,base.end()-12);
  std::cout << str << '\n';         // "fox jumps over"
insert
函数声明功能说明
string& insert (size_t pos, const string& str);在pos位置插入str的副本
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);在pos位置插入str的子串
string& insert (size_t pos, const char* s);在pos位置插入C风格的字符串
string& insert (size_t pos, const char* s, size_t n);在pos位置插入C风格字符串的前n个字符
string& insert (size_t pos, size_t n, char c);void insert (iterator p, size_t n, char c);在pos位置插入n个c
iterator insert (iterator p, char c);在p所指向位置插入字符c
template void insert (iterator p, InputIterator first, InputIterator last);迭代器区间插入

在字符串中pos(或p)指定的字符前面插入额外的字符。

std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
erase
函数声明功能说明
string& erase (size_t pos = 0, size_t len = npos);从pos位置开始删除len个字符
iterator erase (iterator p);迭代器删除字符
iterator erase (iterator first, iterator last);迭代器区间删除
std::string str ("This is an example sentence.");
  std::cout << str << '\n';
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '\n';
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '\n';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '\n';
replace

替代部分字符串

函数声明功能说明
string& replace (size_t pos, size_t len, const string& str);string& replace (iterator i1, iterator i2, const string& str);用str去替换原字符串从pos位置开始len个字符或者替换迭代器区间的所指向的内容
string& replace (size_t pos, size_t len, const string& str,size_t subpos, size_t sublen);用str的子串去替换原字符串的一部分
string& replace (size_t pos, size_t len, const char* s);string& replace (iterator i1, iterator i2, const char* s);用C语言风格字符串去替换原字符串的一部分
string& replace (size_t pos, size_t len, const char* s, size_t n);string& replace (iterator i1, iterator i2, const char* s, size_t n);用C语言风格的字符串的前n个字符去替换原字符串的一部分
string& replace (size_t pos, size_t len, size_t n, char c);string& replace (iterator i1, iterator i2, size_t n, char c);用n个字符c去替换原字符串的一部分
template string& replace (iterator i1, iterator i2, InputIterator first, InputIterator last);用一段迭代器区间的内容去替换目前字符串迭代器区间的部分
std::string base="this is a test string.";
  std::string str2="n example";
  std::string str3="sample phrase";
  std::string str4="useful.";

  // replace signatures used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  std::string str=base;           // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string." (1)
  str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
  str.replace(8,10,"just a");     // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

  // Using iterators:                                               0123456789*123456789*
  str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
  str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
  std::cout << str << '\n';
swap

void swap (string& str);

交换字符串值

	string s1("hello world");
	string s2("你好,世界!");
	s1.swap(s2);
	cout << s1 << endl;//你好,世界!
	cout << s2 << endl;//hello world
pop_back

void pop_back();

删除字符串尾部元素

	string s1("hello world");
	s1.pop_back();//删除尾部元素d
	cout << s1 << endl;//hello worl

字符串运算相关

c_str

const char* c_str() const;

得到C风格字符串

	string s1("hello world");
	cout << s1.c_str() << endl;//hello world
copy

size_t copy (char* s, size_t len, size_t pos = 0) const;

从字符串中复制字符序列

	string s1("helloworld");
	char s2[20];
	//copy(str, n, pos)复制pos位置开始的n个字符到str字符串
	size_t length = s1.copy(s2, 6, 5);
	//copy函数不会在复制内容的末尾附加'\0',需要手动加
	s2[length] = '\0';
	cout << s2 << endl;
find

在字符串中搜索由其参数指定的序列的第一次出现。

函数声明功能介绍
size_t find (const string& str, size_t pos = 0) const;查找第一次出现str,从pos位置开始
size_t find (const char* s, size_t pos = 0) const;查找第一次出现s指向的内容,从pos位置开始
size_t find (const char* s, size_t pos, size_t n) const;从pos开始的前n个字符中查找第一次出现和s指向的内容相同的
size_t find (char c, size_t pos = 0) const;从pos位置开始,查找第一次出现字符c的位置
	string s1("https://blog.csdn.net/2302_79013877?type=blog");
	string s2("csdn");
	cout << s1.find(s2)<< endl;//13
	const char* s3 = "blog";
	cout << s1.find(s3) << endl;//8
	char a = '/';
	cout << s1.find(a);//6
rfind

查找字符串中最后出现的内容

当指定pos时,搜索只包括从位置pos或之前开始的字符序列,忽略从位置pos之后开始的任何可能的匹配。

函数声明功能说明
size_t rfind (const string& str, size_t pos = npos) const;倒着找第一次出现的str的位置
size_t rfind (const char* s, size_t pos = npos) const;倒着找第一次出现与s指向内容相同的位置
size_t rfind (const char* s, size_t pos, size_t n) const;从pos位置开始的n个位置开始找与s指向内容相同的位置
size_t rfind (char c, size_t pos = npos) const;倒着找第一次出现字符c的位置
	string s1("https://blog.csdn.net/2302_79013877?type=blog");
	string s2("csdn");
	cout << s1.rfind(s2)<< endl;//13
	const char* s3 = "blog";
	cout << s1.rfind(s3) << endl;//41
	char a = '/';
	cout << s1.rfind(a);//21
substr

string substr (size_t pos = 0, size_t len = npos) const;

生成子串(返回一个新构造的字符串对象,其值初始化为此对象的子字符串的副本)

	std::string str = "We think in generalities, but we live in details.";
	// (quoting Alfred N. Whitehead)

	std::string str2 = str.substr(3, 5);     // "think"

	std::size_t pos = str.find("live");      // live的位置

	std::string str3 = str.substr(pos);     //live in details.

	std::cout << str2 << ' ' << str3 << '\n';//think live in details.
compare

将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。

函数声明功能说明
int compare (const string& str) const;比较与str字符串是否相等
int compare (size_t pos, size_t len, const string& str) const;int compare (size_t pos, size_t len, const string& str,size_t subpos, size_t sublen) const;从pos位置开始,以len为长度的范围内判断是否和str或者str的子串相等
int compare (const char* s) const;int compare (size_t pos, size_t len, const char* s) const;判断是否和C风格的字符串或者C风格的字符串的子串相等
int compare (size_t pos, size_t len, const char* s, size_t n) const;判断是否和C风格的字符串的前n个字符相等
std::string str1 ("green apple");
  std::string str2 ("red apple");

  if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << '\n';

  if (str1.compare(6,5,"apple") == 0)
    std::cout << "still, " << str1 << " is an apple\n";

  if (str2.compare(str2.size()-5,5,"apple") == 0)
    std::cout << "and " << str2 << " is also an apple\n";

  if (str1.compare(6,5,str2,4,5) == 0)
    std::cout << "therefore, both are apples\n";

//answer
green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples

string中的常量成员

npos就是size_t 的最大值

string中的非成员函数重载

operator++

连接字符串
string operator+ (const string& lhs, const string& rhs);
string operator+ (const string& lhs, const char* rhs);
string operator+ (const char* lhs, const string& rhs);
string operator+ (const string& lhs, char rhs);
string operator+ (char lhs, const string& rhs);

返回一个新构造的字符串对象,其值是lhs中的字符与rhs中的字符的连接。

 std::string firstlevel ("com");
  std::string secondlevel ("cplusplus");
  std::string scheme ("http://");
  std::string hostname;
  std::string url;

  hostname = "www." + secondlevel + '.' + firstlevel;
  url = scheme + hostname;

  std::cout << url << '\n';
swap

交换两个字符串

void swap (string& x, string& y);

	string s1("hello");
	string s2("world");
	swap(s1, s2);
	cout << s1 << " " <<s2<< endl;//world hello
operator>>和 operator<<

istream& operator>> (istream& is, string& str);
ostream& operator<< (ostream& os, const string& str);

流插入

	string s1;
	cin >> s1;
	cout << s1 << endl;
getline (string)

从流中获取行到字符串
getline函数将从is中提取到的字符存储到str中,直到读取到分隔符delim或换行符’\n’为止。

	string s1;
	getline(cin, s1);//My book ?
	cout << s1 << endl;//My book ?
  • 22
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值