C++中的string常用函数集锦

我们直入主题,下面是我今天要讲解的函数列表。

/*
1.查找find系列
2.插入insert系列
3.提取substr
4.删除erase
5.替换replace
*/


现在来看第一个:查找函数。

/*
函数名	                              描述
find	               查找
rfind	               反向查找
find_first_of	       查找包含子串中的任何字符,返回第一个位置
find_first_not_of      查找不包含子串中的任何字符,返回第一个位置
find_last_of	       查找包含子串中的任何字符,返回最后一个位置
find_last_not_of       查找不包含子串中的任何字符,返回最后一个位置
*/
以上函数都是被重载了4次,以下是以find_first_of 函数为例说明他们的参数,其他函数和其参数一样,也就是说总共有24个函数。

/*
size_type find_first_of(const basic_string& s, size_type pos = 0)
size_type find_first_of(const charT* s, size_type pos, size_type n)
size_type find_first_of(const charT* s, size_type pos = 0)
size_type find_first_of(charT c, size_type pos = 0) 
*/
所有的查找函数都返回一个size_type类型,这个返回值一般都是所找到字符串的位置,如果没有找到,则返回string::npos。有一点需要特别注意,所有和string::npos的比较一定要用string::size_type来使用,不要直接使用int 或者unsigned int等类型。其实string::npos表示的是 - 1, 看看头文件:

template <class _CharT, class _Traits, class _Alloc>
const basic_string<_CharT, _Traits, _Alloc>::size_type
basic_string<_CharT, _Traits, _Alloc>::npos
= basic_string<_CharT, _Traits, _Alloc>::size_type) - 1;
这里稍后给出find的使用实例,我们先看最后面的四个。

有这样一个需求:过滤一行开头和结尾的所有非英文字符。看看用string 如何实现:

#include <string>  
#include <iostream>  
using namespace std;
int main() {
	string strinfo = "   //*---Hello Word!......------";
	string strset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	int first = strinfo.find_first_of(strset);
	if (first == string::npos) {
		cout << "not find any characters" << endl;
		return -1;
	}
	int last = strinfo.find_last_of(strset);
	if (last == string::npos) {
		cout << "not find any characters" << endl;
		return -1;
	}
	cout << strinfo.substr(first, last - first + 1) << endl;
	return 0;
}

/*
输出如下:Hello Word
*/
这里把所有的英文字母大小写作为了需要查找的字符集,先查找第一个英文字母的位置,然后查找最后一个英文字母的位置,然后用substr 来的到中间的一部分,用于输出结果。但是个人觉得这个函数能到的地方也就那么几处。比如,Hello和Word中间还有一些字符呢,只能自己写函数去查找了。所以具体问题具体对待,在思考问题时要考虑好,这个函数虽然提供给你,使你更方便的操作代码,但是也要想的全面,函数的功能与你面对的问题是否吻合。或者说这个函数能解决你多少问题,能不能有别的更高效的或者更方便的方法?

好了,下面来看看find函数吧,find函数是正向匹配,也就是找到第一个匹配的字符或字符串。
下面我从两个个方向来说,string中找string和char。

#include<iostream>
#include<string>
#include<algorithm>//find的头文件
using namespace std;
int main()
{
	string str1 = "123456";
	//第一个是string中找string
	string str2 = "34";//能找到的
	string str3 = "364";//找不到的

	int a = str1.find(str2);
	int b = str1.find(str3);
	cout << a << endl;
	cout << b << endl;
	/*
	输出是:
	         2
	        -1
	*/


	//第二个是string中找char
	char ch1 = '3';//能找到的
	char ch2 = '9';//找不到的

	int aa = str1.find(ch1);
	int bb = str1.find(ch2);

	cout << aa << endl;
	cout << bb << endl;
	/*
	输出是:
	       2
	       -1
	*/
	return 0;
}

这里可能会说,如果给的是字符数组呢?例如:从char a[10]="123456789"中查找字符char ch='5'或者char[5]="4567"呢?
http://www.cplusplus.com/reference/cstring/strstr/?kw=strstr   这是C plus plus 的讲解

我们再来看看rfind函数吧,注意这个函数是逆向匹配的,也就是找到最后一个匹配的。

#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
	string str1="456456";

	string str2="456";
	string str3="654";

	int a=str1.rfind(str2);
	int b=str1.rfind(str3);

	cout<<a<<endl;//输出3
	cout<<b<<endl;//输出-1
	return 0;
}
第二个:插入函数

string& insert (size_t pos, const string& str);
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen = npos);
string& insert (size_t pos, const char* s);
string& insert (size_t pos, const char* s, size_t n);	
string& insert (size_t pos,   size_t n, char c);
这是常用的重载。

#include <iostream>
#include <string>

int main ()
{
  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的第6个位置插入str2
  str.insert(6,str3,3,4);             // to be (not )the question在str的第6个位置插入str3的一个片段,为下标为3开始往后的4个字符
  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,3,':');               // to be not to be(:::) that is the question
  std::cout << str << '\n';
  return 0;
}

第三个:提取

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

比较简单,直接看C plus plus给的例子

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                
  std::string str2 = str.substr (3,5);     // "think"
  std::size_t pos = str.find("live");      // position of "live" in str
  std::string str3 = str.substr (pos);     // get from "live" to the end
  std::cout << str2 << ' ' << str3 << '\n';//输出:think live in details.
  return 0;
}
第四个:删除函数

string& erase (size_t pos = 0, size_t len = npos)
iterator erase (iterator p)	
iterator erase (iterator first, iterator last)
还是看下C plus plus 的例子

// string::erase
#include <iostream>
#include <string>
int main()
{
	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." 
	std::cout << str << '\n';
	// "This is a sentence."
	str.erase(str.begin() + 5, str.end() - 9); 
	std::cout << str << '\n';
	// "This sentence."
	return 0;
}

第五个:替换replace

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>//头文件
using namespace std;
int main()
{
	/*函数原型:原型比较多,只写常用的两个
	1.template <class ForwardIterator, class T>
	void replace (ForwardIterator first, ForwardIterator last,const T& old_value, const T& new_value);
	2.basic_string& replace(size_type pos1,size_type n1,const basic_string& str);
	*/
	string str = "take a right turn";
	str.replace(7, 5, "left");//按地址从&str[7]到&str[12]的内容替换为left
	cout << str << endl;//take a left turn

	//注意,也可以使用find()来找出要在replace()中替换的位置
	string s1 = "old";
	string s2 = "mature";
	string s3 = "the old man and the sea";
	int pos = s3.find(s1);
	if (pos != string::npos)
		s3.replace(pos, s1.size(), s2);
	//上述代码把old换成mature

	//再举一个实例
	int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
	vector<int> myvector(myints, myints + 8);            // 10 20 30 30 20 10 10 20
	replace(myvector.begin(), myvector.end(), 20, 99);   // 10 99 30 30 99 10 10 99
	//myvector中所有20换成99
	cout << "myvector contains:";
	for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
		cout << ' ' << *it;
	cout << '\n';
	/*输出:
	myvector contains: 10 99 30 30 99 10 10 99
	*/
	return 0;
}





  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++string类提供了许多常用函数。其一些函数包括: 1. c_str():将string字符转换为C风格的字符,并返回该字符的const指针(const char*)。这个函数可以用于将const string转换为const char*。例如: ```cpp string s1("1234567"); const char* s2 = s1.c_str(); ``` 2. operator\[\]和at():这两个函数都用于访问string的字符。operator\[\]使用索引来访问字符,而at()使用位置来访问字符。例如: ```cpp string str = "abcdefg"; char c1 = str\[0\]; // 使用operator\[\] char c2 = str.at(1); // 使用at() ``` 3. to_string():将数值转换为对应的字符。这个函数可以将整数、浮点数等数值类型转换为string类型。例如: ```cpp int a = 4; double b = 3.14; string str1 = to_string(a); string str2 = to_string(b); ``` 4. 构造函数string类提供了多个构造函数,用于创建string对象。其包括默认构造函数、使用字符常量构造、拷贝构造和数量*字符构造等。例如: ```cpp const char* str = "Hello World"; string s1; // 默认构造 string s2(str); // 使用字符常量构造 string s3("hello World"); // 同上 string s4(s2); // 拷贝构造 string s5(10, 'a'); // 数量*字符 ``` 这些是C++ string类的一些常用函数,可以帮助你在处理字符时更加方便和灵活。 #### 引用[.reference_title] - *1* [C++ string常用函数用法总结](https://blog.csdn.net/qq_61514490/article/details/126165076)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [C++String常用函数总结](https://blog.csdn.net/weixin_51954217/article/details/127990342)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值