當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。