📜  C / C++中的strrchr()函数

📅  最后修改于: 2021-05-30 02:59:02             🧑  作者: Mango

C / C++中的strrchr()函数找到字符串字符的最后一次出现。它返回一个指向字符串最后一次出现的指针。终止的空字符被视为C字符串的一部分。因此,还可以定位它以检索到字符串末尾的指针。它在cstring头文件中定义。
句法 :

const char* strrchr( const char* str, int ch )
            or
char* strrchr( char* str, int ch )

参数:该函数采用两个强制性参数,如下所述:

  • str:指定要搜索的以空终止的字符串的指针。
  • ch:指定要搜索的字符。

返回值:该函数返回一个指针,指向ch的字符串中的最后一个位置,如果通道被发现。如果未找到,则返回空指针。

下面的程序说明了上述函数:

程序1:

// C++ program to illustrate
// the strrchr() function
#include 
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 
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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”