0

函数定位 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
4

3 回答 3

3
return *(s + offset);

您将在此处返回字符s[offset]。您必须将指针返回到该位置,即(s + offset)

return (s + offset);
于 2014-03-19T08:28:46.243 回答
2
const char* strchr_last (const char* s, char ch)
{
  const char* found_at = NULL;

  while(*s != '\0')
  {
    if(*s == ch)
    {
      found_at = s;
    }
    s++;
  }

  return found_at;
}
于 2014-03-19T09:00:32.947 回答
1

您可以执行与查找字符串中第一次出现的字符相同的操作,只需稍作更改:从末尾扫描字符串到开头。

char* strrchr2(char *s, char ch)
{
    char* p = s;
    int found_ch = 0;
    //finding the length of the string
    while (*p != '\0')
    {
        p++;
    }
    //p now points to the last cell in the string
    //finding the first occurrence of ch in s from the end:
    while (p >= s && !found_ch)
    {
        if (*p == ch)
        {
            found_ch = 1;
        }
        else
        {
            p--;
        }
    }
    if (!found_ch)
    {
        p = 0;
    }
    return p;
}
于 2014-03-19T10:04:35.043 回答