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


C语言 strrchr()用法及代码示例


C 中的 strrchr() 函数查找字符串中最后一次出现的字符并返回指向该字符的指针。它是在 <string.h> 头文件中定义的标准库函数。

用法:

char* strrchr( char* str, int chr );

参数:

  • str:指定指向要在其中执行搜索的以 null 结尾的字符串的指针。
  • chr: 指定要搜索的字符。

返回值:

  • 该函数返回一个指向最后一个位置的指针chr在字符串中如果chr被发现。
  • 如果chr没有找到,则返回空指针。

例子:

C


// C program to illustrate
// the strrchr() function
#include <stdio.h>
#include <string.h>
int main()
{
    // initializing string
    char str[] = "GeeksforGeeks";
    // character to be searched
    char chr = 'k';
    // Storing pointer returned by
    char* ptr = strrchr(str, chr);
    // getting the position of the character
    if (ptr) {
        printf("Last occurrence of %c in %s is at index %d",
               chr, str, ptr - str);
    }
    // condition for character not present
    else {
        printf("%c is not present in %s ", chr, str);
    }
    return 0;
}
输出
Last occurrence of k in GeeksforGeeks is at index 11

当字符串中不存在该字符时

如果在给定字符串中找不到搜索的字符,strrchr() 函数将返回 NULL 指针。

例子:

C


// C program to illustrate
// the strrchr() function
#include <stdio.h>
#include <string.h>
int main()
{
    // creating some string
    char str[] = "GeeksforGeeks";
    char* ptr;
    // The character to be searched
    char chr = 'z';
    // pointer returned by strrchr()
    ptr = strrchr(str, chr);
    // ptr-string gives the index location
    if (ptr) {
        printf("Last occurrence of %c in %s is at %d", chr,
               str, ptr - str);
    }
    // If the character we're searching is not present in
    // the array
    else {
        printf("%c is not present in %s ", chr, str);
    }
    return 0;
}
输出
z is not present Geeks for Geeks 

时间复杂度: 在),

空间复杂度:O(1),

其中 n 是字符串的长度。

Note: NULL character is also treated same as other character by strrchr() function, so we can also use it to find the end of the string.



相关用法


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