函数定位 s 指向的字符串中最后一次出现的 ch。它返回一个指向字符的指针,如果字符串中不存在 ch,则返回一个空指针。我正在尝试在不使用字符串库函数的情况下编写函数。
这是我到目前为止得到的,对我来说似乎是正确的,但我似乎无法得到结果字符串。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <math.h>
char *strrchr2(char *s, char ch);
int main()
{
char str1[100];
char char1;
char result_str[100];
printf("\nEnter a string: ");
gets(str1);
fflush(stdin);
printf("Enter the target char in the string: ");
scanf("%c", &char1);
char * result_str = strrchr2(str1, char1);
printf("Resultant string = %s", result_str);
char * strrchr2(char *s, char ch)
{
int count = 0, offset = 0;
while (*(s + count) != '\0')
{
if (*(s + count) == ch)
offset = count;
count++;
}
return *(s + offset);
}
预期输出:
Enter a string: abcdefdfdfghh
Enter the target char in the string: f
Resultant string: fghh