C /C++中的strrchr()函數查找字符串中字符的最後一次出現。它返回一個指向字符串中最後一次出現的指針。終止的空字符被視為C字符串的一部分。因此,還可以定位它以檢索指向字符串末尾的指針。它在cstring頭文件中定義。
用法:
const char* strrchr( const char* str, int ch ) or char* strrchr( char* str, int ch )
參數:該函數采用兩個強製性參數,如下所述:
- str :指定指向要搜索的以空終止的字符串的指針。
- ch: 指定要搜索的字符。
返回值:如果找到ch,該函數將返回指向ch的最後位置的指針。如果找不到,它將返回空指針。
以下示例程序旨在說明上述函數:
示例1:
// C++ program to illustrate
// the strrchr() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Storing it in string array
char string[] = "Geeks for Geeks";
// The character we've to search for
char character = 'k';
// Storing in a pointer ptr
char* ptr = strrchr(string, character);
// ptr-string gives the index location
if (ptr)
cout << "Last position of " << character
<< " in " << string << " is " << ptr - string;
// If the character we're searching is not present in the array
else
cout << character << " is not present "
<< string << endl;
return 0;
}
輸出:
Last position of k in Geeks for Geeks is 13
示例2:
// C++ program to illustrate
// the strrchr() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Storing it in string array
char string[] = "Geeks for Geeks";
char* ptr;
// The character we've to search for
char character = 'z';
// Storing in a pointer ptr
ptr = strrchr(string, character);
// ptr-string gives the index location
if (ptr)
cout << "Last position of " << character
<< " in " << string << " is " << ptr - string;
// If the character we're searching
// is not present in the array
else
cout << character << " is not present in "
<< string << endl;
return 0;
}
輸出:
z is not present in Geeks for Geeks
相關用法
- C++ strrchr()用法及代碼示例
- C++ div()用法及代碼示例
- C++ fma()用法及代碼示例
- C++ log()用法及代碼示例
- C++ valarray abs()用法及代碼示例
- C++ regex_iterator()用法及代碼示例
- C++ map key_comp()用法及代碼示例
- C++ real()用法及代碼示例
- C++ imag()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSrivastava1大神的英文原創作品 strrchr() function in C/C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。