1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| #include <stdio.h> #include <string.h> #include <stdlib.h>
#define TEXT_SIZE 100 #define WORD_SIZE 50 #define DELIMS ",.!?\n "
void replaceWord(const char* text, const char* oldWord, const char* newWord, char* result); int countChar(const char* text, char ch); int countWords(const char* text); void extractUniqueWords(const char* text, char uniqueWords[][WORD_SIZE], int* uniqueCount);
int main(void) { char text[TEXT_SIZE] = "This is a simple text.This text is for texting.";
char replacedText[TEXT_SIZE] = { 0 }; char oldWord[] = "text"; char newWord[] = "example"; char countCharTarget = 's';
char uniqueWords[TEXT_SIZE][WORD_SIZE] = { 0 }; int uniqueCount = 0;
replaceWord(text, oldWord, newWord, replacedText); printf("Repaced Text : %s\n", replacedText);
int charCount = countChar(replacedText, countCharTarget); printf("Character '%c' appears %d times.\n", countCharTarget, charCount);
int wordCount = countWords(replacedText); printf("Total number of words: %d\n", wordCount);
extractUniqueWords(replacedText, uniqueWords, &uniqueCount); puts("Unique words:");
for (int i = 0; i < uniqueCount; i++) { printf("%s\n", uniqueWords[i]); }
return 0; }
void replaceWord(const char* text, const char* oldWord, const char* newWord, char* result) { char buffer[TEXT_SIZE] = { 0 }; const char* pos = text; const char* temp = text; size_t oldlen = strlen(oldWord);
while ((temp = strstr(pos, oldWord)) != NULL) { strncat_s(buffer, sizeof(buffer), pos, temp - pos); strcat_s(buffer, sizeof(buffer), newWord);
pos = temp + oldlen; }
strcat_s(buffer, sizeof(buffer), pos); strcpy_s(result, TEXT_SIZE, buffer); }
int countChar(const char* text, char ch) { int count = 0; while (*text) { if (*text == ch) { count++; } text++; } return count; }
int countWords(const char* text) { int count = 0; char buffer[TEXT_SIZE] = { 0 };
strcpy_s(buffer, TEXT_SIZE, text);
char* context = NULL;
char* token = strtok_s(buffer, DELIMS, &context);
while (token != NULL) { count++; token = strtok_s(NULL, DELIMS, &context); } return count; }
void extractUniqueWords(const char* text, char uniqueWords[][WORD_SIZE], int* uniqueCount) { char tempText[TEXT_SIZE] = { 0 }; strcpy_s(tempText, TEXT_SIZE, text);
char* context = NULL; char* token = strtok_s(tempText, DELIMS, &context);
while (token != NULL) { int found = 0;
for (int j = 0; j < *uniqueCount; ++j) { if (strcmp(token, uniqueWords[j]) == 0) { found = 1; break; } }
if (!found) { strcpy_s(uniqueWords[*uniqueCount], WORD_SIZE, token); (*uniqueCount)++; } token = strtok_s(NULL, DELIMS, &context); } }
|