天天看點

C程式設計語言第二版習題4-1問題描述問題分解代碼實作編譯運作

問題描述

編寫一個函數strrindex(s, t),用于傳回字元串t在s中最右出現的位置,如果 s中不 包含t,那麼傳回-1。

問題分解

  • 主函數main
  • 工具函數 get_line(s, max), 注意不能按照書上的getline,因為getline 已經在頭檔案stdio.h定義了
  • 核心函數 strrindex(source, searchfor)。這道題是根據書中strindex例子進行變化,我們先來看看strindex的程式實作:
int strindex(char s[], char t[])
{
        int i, j, k;
        for(i = 0; s[i] != '\0'; i++){
                for(j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
                        ;
​
                if(k > 0 && t[k] == '\0'){
                    return i;
                }
        }
        return -1;
}           

分析strindex可以發現,這個函數是隻要在source中發現searchfor字元串,就傳回目前的i,即傳回所查找字元串的第一次出現的位置。我們現在要尋找的是最後一次出現的位置,是以我們對strindex進行修改,取消第9行的return,取而代之使用一個變量pos來承接每次出現searchfor的位置,是以pos會及時更新,直到source周遊結束。

代碼實作

#include<stdio.h>
​
#define MAXLINE 100
​
int get_line(char s[], int max);
int strrindex(char source[], char searchfor[]);
char pattern[] = "ould";
​
int main()
{
        char line[MAXLINE];
        int found = 0, pos;
​
        while(get_line(line, MAXLINE) > 0){
                if((pos = strrindex(line, pattern)) >= 0){
                        printf("The position is :%d \n", pos);
                        found++;
                }
​
        }
        return found;
}
​
int get_line(char s[], int max)
{
        int i = 0;
        char c;
​
        while(--max > 0 && (c = getchar()) != '\0' && c != '\n'){
                s[i++] = c;
        }
        if(c == '\n'){
                s[i++] = c;
        }
        s[i] = '\0';
        return i;
}
​
int strrindex(char s[], char t[])
{
        int i, j, k, pos = -1;
        for(i = 0; s[i] != '\0'; i++){
                for(j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
                        ;
​
                if(k > 0 && t[k] == '\0'){
                    pos = i;
                }
        }
        return pos;
}           

編譯運作

C程式設計語言第二版習題4-1問題描述問題分解代碼實作編譯運作

運作結果可看出,達到了預期的。

繼續閱讀