C++String中的find用法



#include<string>

string 是c++中一個非常重要函數。

在處理字符串的時候經常用到。

find是string中一個查找函數。

find用法:

1.find()

示例:(上代碼)

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string a;
	string b;
	
	getline(cin,a);
	getline(cin,b);
	
	int post=b.find(a);
	
	cout<<post<<endl;
	return 0;
}

首先定義兩個string類型的變量a和b,getline()是string中的一個方法,從鍵盤讀取一行。

b.find(a);這句代碼的意思就是從b字符串中查找a字符串。

公式可以理解為————>母字符串.find(子字符串);

返回值的類型為int類型,返回的是字符串的下標。

#include<iostream>
#include<string>
using namespace std;
int main()
{

 	string st1("babbabab");
    cout << st1.find('a') << endl;//1   由原型知,若省略第2個參數,則默認從位置0(即第1個字符)起開始查找
    cout << st1.find('a', 0) << endl;//1
    cout << st1.find('a', 1) << endl;//1   
    cout << st1.find('a', 2) << endl;//4

    return 0;
}

st1.find('a',1);后面的數字代表從什么位置開始查找。如果不加,默認從位置0(即第一個字符)開始查找。

如果你要查找的字符不是單個字母,用法和查找單個字母一樣,它會返回第一個字符的位置。

 

2.rfind()

rfind()就是倒着查找。。。。

后面的數字代表着就是從倒數第幾個開始查找。

 

 

在這里說一下,如果計算機沒有找到,就會返回npos!!

 

	if(b.find(a)==string::npos)
	{
		cout<<"no find"<<endl;
	}

比如說看這個代碼,,如果返回值等於npos,就說明在b字符串里面,沒有找到a。

 

3.find_first_of()

        在源串中從位置pos起往后查找,只要在源串中遇到一個字符,該字符與目標串中任意一個字符相同,就停止查找,返回該字符在源串中的位置;若匹配失敗,返回npos。

示例

//將字符串中所有的元音字母換成*
//代碼來自C++ Reference,地址:http://www.cplusplus.com/reference/string/basic_string/find_first_of/
#include<iostream>
#include<string>

using namespace std;

int main()
{
    std::string str("PLease, replace the vowels in this sentence by asterisks.");
    std::string::size_type found = str.find_first_of("aeiou");
    while (found != std::string::npos)
    {
        str[found] = '*';
        found = str.find_first_of("aeiou", found + 1);
    }
    std::cout << str << '\n';
    return 0;
}
//運行結果:
//PL**s* r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks

4.find_last_of()

 

函數與find_first_of()函數相似,只不過查找順序是從指定位置向前。

 

5.find_first_not_of()


      在源串中從位置pos開始往后查找,只要在源串遇到一個字符,該字符與目標串中的任意一個字符都不相同,就停止查找,返回該字符在源串中的位置;若遍歷完整個源串,都找不到滿  足條件的字符,則返回npos。

示例

#include<iostream>
#include<string>

using namespace std;

int main()
{
    //測試size_type find_first_not_of (const charT* s, size_type pos = 0) const;
    string str("abcdefg");
    cout << str.find_first_not_of("kiajbvehfgmlc", 0) << endl;//3   從源串str的位置0(a)開始查找,目標串中有a(匹配),再找b,b匹配,再找c,c匹配,
                                                              //    再找d,目標串中沒有d(不匹配),停止查找,返回d在str中的位置3
    return 0;
}

可以復制下來,自己驗證一下。

6.find_last_not_of()

find_last_not_of()與find_first_not_of()相似,只不過查找順序是從指定位置向前。

 

 

                                                                                                               借鑒:https://www.cnblogs.com/zpcdbky/p/4471454.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM