Last active
April 18, 2017 12:20
-
-
Save ebal5/4d31462357f287e6967f2c163527b807 to your computer and use it in GitHub Desktop.
部分的だけど実装部
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
#include <assert.h> | |
#define MAX_LENGTH 255 /* 設定上の最大文字数 */ | |
#define NUM_OF_TGT 3 | |
int search(char *word, char *str); | |
int main(void){ | |
/* 変数宣言 */ | |
FILE *fp; | |
char *str; | |
char words[NUM_OF_TGT][8] = | |
{"Alice", "wonder", "self"}; /* 対象文字列の配列 */ | |
int counter[NUM_OF_TGT] = {0};/* カウント変数 wordsの順に対応 */ | |
int i; /* 制御変数 */ | |
char testStr[] = " They were indeed a queer-looking party that assembled on the"; | |
/* 文字列格納用の配列をMAX_LENGTH文字分確保 */ | |
str = (char *)malloc(MAX_LENGTH*sizeof(char)); | |
assert(str != NULL); | |
/* ファイルを開けなければ異常終了 */ | |
if((fp = fopen("./Alice_in_Wonderland.txt","r")) == NULL){ | |
fprintf(stderr, "Can't open the file\n"); | |
fprintf(stderr, "Will be exit abnormally\n"); | |
exit(1); | |
} | |
/* 各行について探索を行う */ | |
printf("searching...\n"); | |
/* while((fgets(str, MAX_LENGTH, fp)) != NULL){ */ | |
/* for(i = 0; i < NUM_OF_TGT; i++){ */ | |
/* counter[i] += search(words[i], str); */ | |
/* } */ | |
/* } */ | |
search(words[1], testStr); | |
printf("done\n"); | |
printf("results::\n"); | |
for(i = 0; i < NUM_OF_TGT; i++){ | |
printf("%s :: %d\n", words[i], counter[i]); | |
} | |
fclose(fp); /* fpで開かれたファイルのクローズ処理 */ | |
return 0; | |
} | |
/* | |
文字列の長さをカウントする関数 | |
ただし最終文字が改行の場合はヌル文字に置き換えられる | |
*/ | |
int length(char *str){ | |
int len = 0; | |
for(;;){ | |
if(str[len] == '\0' || str[len] == '\n'){ | |
str[len] = '\0'; | |
break; | |
}else{ | |
len++; | |
} | |
} | |
return len; | |
} | |
/* wordで指定された文字列をstrで指定された文字列から探す関数 */ | |
/* 戻り値は発見された数 */ | |
int search(char *word, char *str){ | |
/* 変数宣言 */ | |
int lengthOfWord = length(word); /* wordの長さ */ | |
int lengthOfStr = length(str); /* strの長さ */ | |
int i,j; /* 制御変数 */ | |
int count = 0; /* 発見個数 */ | |
printf("search \"%s\" in \"%s\"\n", word, str); | |
/* ずらし表の作成 */ | |
for(i = 0; i < CHAR_MAX; i++){ | |
withes[i] = lengthOfWord; | |
} | |
for(i = 0; i < lengthOfWord; i++){ | |
withes[(int)word[i]] = (lengthOfWord-1) - i; | |
} | |
printf("%d\n", withes[(int)'e']); | |
/* 照合 */ | |
printf("%5s %5s\n", "i", "j"); | |
i = (lengthOfWord-1); | |
while(i < lengthOfStr && j >= 0){ | |
j = lengthOfWord-1; | |
printf("%5d %5d\n", i, j); | |
if(str[i] == word[j]){ | |
i--; | |
j--; | |
}else{ | |
i += withes[(int)str[i]]; | |
j = lengthOfWord - 1; | |
} | |
if(j == -1){ | |
count++; | |
i += lengthOfWord + 1; | |
} | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment