[c罗]C++ string 字符串查找函数

更新时间:2020-11-10    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

在写C++程序中,总会遇到要从一个字符串中查找一小段子字符串的情况,对于在C中,我们经常用到strstr()或者strchr()这两种方法。而对于C++的string,我们往往会用到find()。

C++:#inlcude

C: #include

find():在一个字符串中查找一个指定的单个字符或字符数组。如果找到,就返回首次匹配的开始位置;如果没有查找到匹配的内容,就返回string::npos。

find_first_of():在一个目标串中进行查找,返回值是第一个与指定字符组中任何字符匹配的字符位置。如果没有查找到匹配的内容,则返回npos。

find_last_of():在一个目标串中进行查找,返回最后一个与指定字符组中任何字符匹配的字符位置。如果没有查找到匹配的内容,则返回npos。

find_first_not_of():在一个目标串中进行查找,返回第一个与指定字符组中任何字符都不匹配的元素位置。如果找不到那样的元素则返回npos。

find_last_not_of():在一个目标串中进行查找,返回下标值最大的与指定字符组中任何字符都不匹配的元素的位置。若找不到那样的元素则返回npos。

rfind():对一个串从尾至头查找一个指定的单个字符或字符组。如果找到,就返回首次匹配的开始位置;如果没有查找到匹配的内容,则返回npos。

find(string, int):第一个参数用来指示要查找的字符,第二个参数用来表示从字符串的何处开始查找子串(默认的查找位置是0)。

举例:字符串匹配:

 代码如下

#include "stdafx.h"

#include<iostream>

#include

#include

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

string T;//原串

string P;//模式

while(cin>>T>>P)

{

int count=0;

int begin=-1;

while((begin=T.find(P,begin+1))!=string::npos)

{

count++;

}

cout<

}

int z;

cin>>z;

return 0;

}


运行结果为:

The string to search is "Heartbeat"
Element in "abcde" found at position 1
Element in "abcde" found at position 2
Element in "aeiou" found at position 6
Element in "aeiou" found at position 1
"e" found at position 6


例子

 代码如下

#include<iostream>
#include

using namespace std;

int main()
{
 string s = "**Gteate Wall**!";
 string t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 cout<<"s: "<  cout<<"t: "<

 int first=s.find_first_of(t);

 if(first == string::npos){
  cout<<"s中所有字符均不在t中"<  }else {
  cout<<"s中出现在t中的字符的第一个字符:"<  }

 int last = s.find_last_of(t);
 if(last == string::npos){
  cout<<"s中所有字符均不在t中"<   return 1;
 }else {
  cout<<"s中出现在t的字符的最后一个字符:"<   return 1;
 }

}


查找

string str;
cin >> str;

str.find("ab");//返回字符串 ab 在 str 的位置
str.find("ab", 2);//在 str[2]~str[n-1] 范围内查找并返回字符串 ab 在 str 的位置
str.rfind("ab", 2);//在 str[0]~str[2] 范围内查找并返回字符串 ab 在 str 的位置

//first 系列函数
str.find_first_of("apple");//返回 apple 中任何一个字符首次在 str 中出现的位置
str.find_first_of("apple", 2);//返回 apple 中任何一个字符首次在 str[2]~str[n-1] 范围中出现的位置
str.find_first_not_of("apple");//返回除 apple 以外的任何一个字符在 str 中首次出现的位置
str.find_first_not_of("apple", 2);//返回除 apple 以外的任何一个字符在 str[2]~str[n-1] 范围中首次出现的位置

//last 系列函数
str.find_last_of("apple");//返回 apple 中任何一个字符最后一次在 str 中出现的位置
str.find_last_of("apple", 2);//返回 apple 中任何一个字符最后一次在 str[0]~str[2] 范围中出现的位置
str.find_last_not_of("apple");//返回除 apple 以外的任何一个字符在 str 中最后一次出现的位置
str.find_last_not_of("apple", 2);//返回除 apple 以外的任何一个字符在 str[0]~str[2] 范围中最后一次出现的位置

//以上函数如果没有找到,均返回string::npos
cout << string::npos;

本文来源:http://www.bbyears.com/jiaocheng/109456.html