【substr()】 substr()是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾。 语法
substr(size_type _Off = 0,size_type _Count = npos) 运行结果:
#include #include using namespace std; int main() { string s = "1234"; // 一共5个字节 string a = s.substr(); // 1234 空就取全部 string b = s.substr(1); // 234 从1开始取到尾巴 string c = s.substr(0, 3); // 123 从0取3个字节 string d = s.substr(1, 9); // 234 超过范围也取到尾巴 cout << a << endl; cout << b << endl; cout << c << endl; cout << d << endl; system("pause"); return 0; } 【find()】 语法: InputIterator find (InputIterator first, InputIterator last, const T& val);
1234 234 123 234 运行结果:
#include #include using namespace std; int main() { // 012345678901234567890 string str1 = "I love you. I love!"; string str2 = "love"; // 若str2 是 str1 的子字符串,返回其在 str1 中第一次出现的位置。 // 若找不到 str2,则返回 -1。 int pos = str1.find(str2, 3); // find对大小写敏感love和Love是不一样的。 // 从下标0找:str1.find(str2,0); 结果pos=2 也可以写成 str1.find(str2); // 从下标3找:str1.find(str2,3); 结果pos=14 if (pos != -1) cout << "pos=" << pos << endl; else cout << "Not found!" << endl; system("pause"); return 0; } 【rfind()】 rfind() 和 find() 很类似,只是反着查。
pos=14 运行结果:
#include #include using namespace std; int main() { // 012345678901234567890 string str1 = "I love you. I love!"; string str2 = "love"; // 若str2 是 str1 的子字符串,返回其在 str1 中第一次出现的位置; // 若找不到 str2,则返回 -1 int pos = str1.rfind(str2); // 从下标0找:str1.find(str2); 结果pos=14 // 从下标9找:str1.find(str2,9); 结果pos=2 cout << "From end: " << str1.rfind(str2) << endl; cout << "From 9: " << str1.rfind(str2, 9) << endl; system("pause"); return 0; } 【举例:统计子字符串在主字符串出现的次数】
From end: 14 From 9: 2 运行结果:
#include #include using namespace std; int f_get_count(string str1, string str2) { // 得到次数的函数 // 确定主串,子串长度 int intStr1Len = str1.length(), intStr2Len = str2.length(); if (intStr1Len > intStr2Len) // 保证子串长度小于主串长度 { int intCount = 0; // 次数 int intPos = 0; // 检索的起始位置 int intStart = 0; // 中间变量 // 子串在主串中从pos处开始最先出现的位置 while ((intStart = str1.find(str2, intPos)) != -1) { intCount++; intPos = intStart + intStr2Len; // 更新起始位置,检索位置+子串串长 } return intCount; } return 0; } int main() { string str1 = "baishizhidao.com"; string str2 = "hi"; int intCount = f_get_count(str1, str2); cout << "Times=" << intCount << endl; system("pause"); return 0; }
Times=2