**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();
}