当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ strrchr()用法及代码示例


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


相关用法


注:本文由纯净天空筛选整理自AmanSrivastava1大神的英文原创作品 strrchr() function in C/C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。