字元检查请教
想编写一个从char*检查特定字元, 但无从入手, 请各大神指教一下例: 检查字元是 'is'
int countResult(char source[])
{
}
int main()
{
char* source = "This is an apple";
int count = 0;
count = countResult(source);
printf("Result: %d", count)//Output: Result: 2
}
#include <stdio.h> typedef int BOOL; #define FALSE 0 #define TRUE 1 BOOL is_space(const char ch); BOOL string_compare(const char* source, const char* target); int countResult(const char* source, const char* target); int main(void) { const char* source = "This is an apple"; const char* target = "is"; printf_s("Source string: %s\n", source); printf_s("Target string: %s\n", target); printf_s("Result: %d\n", countResult(source, target)); getchar(); return 0; } BOOL is_space(const char ch) { return (ch == ' ') || (ch == '\t') || (ch == '\r') || (ch == '\n'); } BOOL string_compare(const char* source, const char* target) { BOOL is_equivalent = TRUE; // 空串與任何串相等 while (*target != '\0') { if (*source++ != *target++) { is_equivalent = FALSE; break; } } return is_equivalent; } int countResult(const char* source, const char* target) { int count = 0; BOOL in_word = FALSE; if (*source == '\0') { return count; } while (*source != '\0') { if (!is_space(*source) && !in_word) { in_word = TRUE; if (string_compare(source, target)) { break; } } if (is_space(*source) && in_word) { ++count; in_word = FALSE; } ++source; } return count + 1; }
#include <stdio.h> typedef int BOOL; #define FALSE 0 #define TRUE !0 BOOL is_space(const char ch); BOOL string_compare(const char* source, const char* target); int countResult(const char* source, const char* target); int main(void) { const char* source = "This is an apple"; const char* target = "is"; printf_s("Source string: %s\n", source); printf_s("Target string: %s\n", target); printf_s("Result: %d\n", countResult(source, target)); getchar(); return 0; } BOOL is_space(const char ch) { return (ch == ' ') || (ch == '\t') || (ch == '\r') || (ch == '\n') ? TRUE : FALSE; } BOOL string_compare(const char* source, const char* target) { BOOL is_equivalent = TRUE; // 空串與任何串相等 while (*target != '\0') { if (*source++ != *target++) { is_equivalent = FALSE; break; } } return is_equivalent; } int countResult(const char* source, const char* target) { int count = 0; BOOL in_word = FALSE; BOOL found = FALSE; while (*source != '\0') { if (!is_space(*source) && !in_word) { in_word = TRUE; if (string_compare(source, target)) { found = TRUE; break; } } if (is_space(*source) && in_word) { ++count; in_word = FALSE; } ++source; } return found ? count + 1 : 0; }