2014-03-19 237 views
0

函數查找由s指向的字符串中ch的最後出現次數。它返回一個指向字符的指針,或者如果字符串中不存在ch,則返回一個空指針。我試圖編寫函數而不使用字符串庫函數。使用指針(C語言)查找字符串中最後一次出現的字符

這就是我到目前爲止,它似乎對我來說,但我似乎無法得到結果字符串。

#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 
+3

您聲明瞭'result_str'兩次!! –

+2

你的編譯器應該在'return *(s + offset);'行發出一個錯誤。因爲'不能從'char'轉換爲'char *'' –

+1

'fflush(stdin)'是未定義的行爲。 'fflush(stdout)'很好,儘管 –

回答

3
return *(s + offset); 

您在這裏返回字符s[offset]。你必須在指針回到這個位置是(s + offset)

return (s + offset); 
+0

...一旦修復,如果字符串中不存在字符,仍然無法返回空指針 – mfro

+0

@mfro我真的不知道如何返回空指針,我可以放* s ='\ 0'然後在else部分返回s? – unintendedjoy

+0

@unintendedjoy你的方向是錯的。 – zoska

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; 
} 
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; 
} 
+1

這可能是更好的只是遍歷字符串一次,如我的答案。在最壞的情況下,只能在字符串的最開始搜索字母,您的代碼將不得不遍歷整個字符串兩次:第一次前進,然後後退。該算法執行得更好的唯一情況是搜索到的符號始終預期位於該字符串的末尾。 – Lundin

相關問題