0

関数は、s が指す文字列内で最後に出現する ch を見つけます。文字へのポインターを返すか、文字列に ch が存在しない場合は null ポインターを返します。文字列ライブラリ関数を使用せずに関数を記述しようとしています。

これは私がこれまでに得たものです。私には正しいようですが、結果の文字列を取得できないようです。

#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 に答える
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 に答える