演習4-1 K&R プログラミング言語C

演習4-1

行の最後尾、探索文字の後ろから探していく。

#include <stdio.h>
#include <string.h>
#define MAXLINE 1024

int getline(char line[], int max);
int strrindex(char source[], char searchfor[]);

char pattern[] = "hello";

int main(int argc, char *argv[])
{
    char line[MAXLINE];
    int i;
    int pos = 0;
    int found = 0;

    while (getline(line, MAXLINE) > 0) {
        if ((pos = strrindex(line, pattern)) >= 0) {
            printf("      ");
            for (i = 0; i < pos+1; i++) {
                printf("%d", i % 10);
            }
            printf("\n");
            printf("%3d : %s", pos, line);
            found++;
        }
    }

    return found;
}

/* getline : s に行を入れ、長さを返す */
int getline(char s[], int lim)
{
    int c, i;

    i = 0;
    while (--lim > 0 && (c = getchar()) != EOF && c != '\n') {
        s[i++] = c;
    }
    if (c == '\n') {
        s[i++] = c;
    }
    s[i] = '
#include <stdio.h>
#include <string.h>
#define MAXLINE 1024

int getline(char line[], int max);
int strrindex(char source[], char searchfor[]);

char pattern[] = "hello";

int main(int argc, char *argv[])
{
    char line[MAXLINE];
    int i;
    int pos = 0;
    int found = 0;

    while (getline(line, MAXLINE) > 0) {
        if ((pos = strrindex(line, pattern)) >= 0) {
            printf("      ");
            for (i = 0; i < pos+1; i++) {
                printf("%d", i % 10);
            }
            printf("\n");
            printf("%3d : %s", pos, line);
            found++;
        }
    }

    return found;
}

/* getline : s に行を入れ、長さを返す */
int getline(char s[], int lim)
{
    int c, i;

    i = 0;
    while (--lim > 0 && (c = getchar()) != EOF && 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, s_pos, t_pos;

    s_pos = strlen(s) - 1;
    t_pos = strlen(t) - 1;
    for (; s_pos >= 0; s_pos--) {
        for (i = s_pos, j = t_pos; j >= 0 && s[i] == t[j]; i--,j--) {
        }
        if (j == -1) {
            return i + 1;
        }
    }
    return -1;
}
'
; return i; } int strrindex(char s[], char t[]) { int i, j, s_pos, t_pos; s_pos = strlen(s) - 1; t_pos = strlen(t) - 1; for (; s_pos >= 0; s_pos--) { for (i = s_pos, j = t_pos; j >= 0 && s[i] == t[j]; i--,j--) { } if (j == -1) { return i + 1; } } return -1; }

実行結果

$ ./ex4-1 <sample2.txt
      012345678901234
 14 : hello, hello, hello, world.
      01234567
  7 : hello, hello, llo, world.
      0
  0 : hello, he, llo, world.
プログラミング言語C 第2版 ANSI規格準拠
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
«
»