c++的std::string类型的内建功能

**1.提取字符串
函数 substr
ps:一个中 文相当两个英语

#include <iostream>

#include <string>

using namespace std ;

void main()

{

    string s="ABAB";

    cout << s.substr(2) <<endl ; //输出AB

    cout << s.substr(0,2) <<endl ; //同上

    cout << s.substr(1,2) <<endl ; //输出BA

}

2.比较字符串*** compare 若参与比较的两个串值相同,则函数返回 0;若字符串 S 按字典顺序要先于 S2,则返回负值;反之,则返回正值。下面举例说明如何使用 string 类的 compare() 函数。
字典顺序就是ASCII顺序,就是内码顺序***

#include<iostream>
#include<string>
int main()
{
	std::string str1="hello";
	std::string str2 = "hellc";
	int m1 = str1.compare(str2);//完整的str1与str2的比较
	int m2 = str1.compare(1,3,str2,2,4);//ell与llc的比较
	int m3 = str1.compare(0, 3, str2, 0, 3);//hell与hell的比较
	std::cout << m1 << std::endl << m2<<std::endl<<m3;
	std::cin.get();
}

3.添加字符串
可以直接添加

#include<iostream>
#include<string>
int main()
{
	std::string str1="hello";
	std::string str2 = "hellc";
	for (int i = 0; i < 100; i++)
	{
		str1 += str2;
	}
	std::cout << str1 << std::endl;
	std::cin.get();
}

使用insert函数

#include<iostream>
#include<string>
int main()
{
	std::string str1="hello";

	for (int i = 0; i < 100; i++)
	{
		str1.insert(0, "hello");
	}
	std::cout << str1 << std::endl;
	std::cin.get();
}

4.搜索字符串
s.find(s1) //查找s中第一次出现s1的位置,并返回(包括0)
s.rfind(s1) //查找s中最后次出现s1的位置,并返回(包括0)
s.find_first_of(s1) //查找在s1中任意一个字符在s中第一次出现的位置,并返回(包括0)
s.find_last_of(s1) //查找在s1中任意一个字符在s中最后一次出现的位置,并返回(包括0)
s.fin_first_not_of(s1) //查找s中第一个不属于s1中的字符的位置,并返回(包括0)
s.fin_last_not_of(s1) //查找s中最后一个不属于s1中的字符的位置,并返回(包括0)

#include <iostream>
#include <string>
int main()
{
	std::string str("hello my world");
	std::cout<<str.find('m')<<std::endl;
	std::cin.get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值