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

这个 strrchr() 函数查找字符串中最后出现的字符。它返回一个指向字符串中最后一次出现的指针。终止的空字符被认为是C字符串的一部分。因此,也可以定位它来检索指向字符串结尾的指针。定义见 cstring 头文件。 语法:

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

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

  • str: 指定指向要搜索的以null结尾的字符串的指针。
  • 中国: 指定要搜索的字符。

返回值: 函数返回一个指针,指向 中国 如果 中国 找到了。如果未找到,则返回空指针。

以下程序说明了上述功能:

项目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

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享