strrchr
- Locate last occurrence of character in string, Returns a pointer to the last occurrence of character in the C string str.
- The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.
- 尋找 ch (如同用 (char)ch 轉換到 char 後)在 str 所指向的空終止位元組串中(將每個字元轉譯成 unsigned char )的最後出現。若搜尋 `0` ,則認為終止空字元為字串的一部分,而且能找到。
- C 庫函式 char strrchr(const char str, int c) 在引數 str 所指向的字串中搜尋最後一次出現字元 c(一個無符號字元)的位置。
- 若 str 不是指向空終止位元組串的指標,則行為未定義。
char *strrchr( const char *str, int ch );
Parameters
str
- C string.
- 指向要分析的空終止位元組字串的指標
character
- Character to be located. It is passed as its int promotion, but it is internally converted back to char.
- 要搜尋的字元
- 要搜尋的字元。以 int 形式傳遞,但是最終會轉換回 char 形式。
Return Value
- A pointer to the last occurrence of character in str.If the character is not found, the function returns a null pointer.
- 指向 str 中找到的字元的指標,或若找不到這種字元則為空指標。
- 該函式返回 str 中最後一次出現字元 c 的位置。如果未找到該值,則函式返回一個空指標。
Example
//
// Created by zhangrongxiang on 2018/2/6 9:12
// File strrchr
//
#include <stdio.h>
#include <string.h>
//該函式返回 str 中最後一次出現字元 c 的位置。如果未找到該值,則函式返回一個空指標。
int main() {
const char str[] = "https://github.com/zhangrxiang/learn-c";
const char str2[] = "D:\WorkSpace\clionProjects\learn-c\string\strrchr.c";
const char ch = `/`;
const char ch2 = `\`;
char *ret;
ret = strrchr(str, ch);
// |/| ------ |/learn-c|
printf("|%c| ------ |%s|
", ch, ret);
printf("%c
", ret[0]);// /
printf("%ld
", ret - str + 1);//number 31
printf("%ld
", ret - str);//index 30
ret = strrchr(str2, ch2);
// || ------ |strrchr.c|
printf("|%c| ------ |%s|
", ch2, ret);
printf("%c
", ret[0]); /*** */
printf("%c
", str2[ret - str2]);/*** */
printf("%ld
", ret - str2 + 1);//42
printf("%d
", (int) strlen(ret));//10
printf("%s
", ret + 1);//strrchr.c
printf("%c
", *ret); /*** */
printf("%c
", *(ret + sizeof(char)));//s
printf("%c
", *(ret + sizeof(char) * 2));//t
printf("%s
", &(*ret));// strrchr.c
printf("%s
", &*(ret + sizeof(char)));//strrchr.c
ret = strrchr(str,`A`);
if (ret){
printf("exists A
");
} else{
// no exists A
printf("no exists A
");
}
return 0;
}
參考文章
轉載註明出處