#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
static bool read_from_stdin(char* buffer, const size_t size)
{
char* result;
int index = 0;
if (size <= 0) {
return false;
}
result = fgets(buffer, size, stdin);
if (result == NULL) {
buffer[index] = '\0';
return false;
}
index = strlen(buffer) - 1;
if (buffer[index] == '\n') {
buffer[index] = '\0';
}
return result != NULL;
}
static bool read_sentence(char* sentence, const size_t size)
{
printf("英文を入力してください:\n");
return read_from_stdin(sentence, size);
}
static bool read_word(char* word, const size_t size)
{
printf("数を調べたいアルファベットを入力してください: \n");
return read_from_stdin(word, size);
}
static int count_needle(const char* haystack, const char* needle)
{
char* found;
int result = 0;
if (strlen(needle) == 0) {
return 0;
}
found = strstr(haystack, needle);
while (found != NULL) {
found = strstr(found + strlen(needle), needle);
++result;
}
return result;
}
static void print_result(const char* sentence, const char* word)
{
const int count = count_needle(sentence, word);
printf("「%s」という英文の中には %s が %d 文字あります。", sentence, word, count);
}
int main(int argc, char const* argv[])
{
const size_t BUFFER_SIZE = 1024;
char sentence[BUFFER_SIZE];
char word[BUFFER_SIZE];
if (!read_sentence(sentence, BUFFER_SIZE)) {
printf("英文の読み込みに失敗しました。");
exit(-1);
}
if (!read_word(word, BUFFER_SIZE)) {
printf("文字の読み込みに失敗しました。");
exit(-1);
}
print_result(sentence, word);
return 0;
}
$ gcc -g -Wall -std=c99 -o main main.c
$ ./main
英文を入力してください:
He associate with a stone
数を調べたいアルファベットを入力してください:
s
「He associate with a stone」という英文の中には s が 3 文字あります。