String查找子串和字符
string 类有一些查找子串和字符的成员函数,它们的返回值都是子串或字符在 string 对象字符串中的位置(即下标)。如果查不到,则返回 string::npos。string: :npos 是在 string 类中定义的一个静态常量。这些函数如下:
- find:从前往后查找子串或字符出现的位置。
- rfind:从后往前查找子串或字符出现的位置。
- find_first_of:从前往后查找何处出现另一个字符串中包含的字符。例如:
- s1.find_first_of("abc"); //查找s1中第一次出现"abc"中任一字符的位置
- find_last_of:从后往前查找何处出现另一个字符串中包含的字符。
- find_first_not_of:从前往后查找何处出现另一个字符串中没有包含的字符。
- find_last_not_of:从后往前查找何处出现另一个字符串中没有包含的字符。
下面是 string 类的查找成员函数的示例程序。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("Source Code");
int n;
if ((n = s1.find('u')) != string::npos) //查找 u 出现的位置
cout << "1) " << n << "," << s1.substr(n) << endl;
//输出 l)2,urce Code
if ((n = s1.find("Source", 3)) == string::npos)
//从下标3开始查找"Source",找不到
cout << "2) " << "Not Found" << endl; //输出 2) Not Found
if ((n = s1.find("Co")) != string::npos)
//查找子串"Co"。能找到,返回"Co"的位置
cout << "3) " << n << ", " << s1.substr(n) << endl;
//输出 3) 7, Code
if ((n = s1.find_first_of("ceo")) != string::npos)
//查找第一次出现或 'c'、'e'或'o'的位置
cout << "4) " << n << ", " << s1.substr(n) << endl;
//输出 4) l, ource Code
if ((n = s1.find_last_of('e')) != string::npos)
//查找最后一个 'e' 的位置
cout << "5) " << n << ", " << s1.substr(n) << endl; //输出 5) 10, e
if ((n = s1.find_first_not_of("eou", 1)) != string::npos)
//从下标1开始查找第一次出现非 'e'、'o' 或 'u' 字符的位置
cout << "6) " << n << ", " << s1.substr(n) << endl;
//输出 6) 3, rce Code
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(int agrc, char** argv)
{
string s1;
//char a[] = "你好!前进,后退,停止,我是机器人!哈哈哈";
char* a = "你好!前进,后退,停止,我是机器人!哈哈哈";
s1 = a; //把字符串给到S1
cout<<s1<<endl; //输出S1
int n;
if((n = s1.find("机")) != string::npos)
{
cout<< n << ","<<s1.substr(n)<<endl;
}
n = s1.find("机"); //在S1中找“机”的位置并输出,如果没有就为-1
cout<<n<<endl;
return 0;
}
添加查长度功能:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(int agrc, char** argv)
{
string s1;
//s1 = ("你好!前进,后退,停止,我是机器人!哈哈哈");
//char a[] = "你好!前进,后退,停止,我是机器人!哈哈哈";
char* a = "你好!前进,后退,停止,我是机器人!哈哈哈";
s1 = a; //把字符串给到S1
cout<<s1<<endl; //输出S1
int n;
if((n = s1.find("机")) != string::npos)
{
cout<< n << ","<<s1.substr(n)<<endl;
}
n = s1.find("机"); //在S1中找“机”的位置并输出,如果没有就为-1
cout<<n<<endl;
cout<<"--------------"<<endl;
string s2;
char b[200] = "你好!前进,后退,停止,我是机器人";
cout<<"b.len"<<strlen(b)<<endl; //char型字符串查长度
s2 = b;
cout<<"s2.len"<<s2.length()<<endl; //string型查长度
return 0;
}