这个程序使用了一个自定义的函数 replaceKeywordsWithEmoticons,它会遍历输入字符串中的每个字符,并检查是否存在一个关键词。如果找到关键词,它会将其替换成一个随机的颜文字表情。如果没有找到关键词,它会将该字符复制到输出字符串中。程序使用 strncmp 函数来比较字符串,这比 strstr 函数更加高效。程序中还使用了宏定义和数组来简化代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NUM_KEYWORDS 6
#define MAX_KEYWORD_LEN 10
#define MAX_EMOTICON_LEN 10
char keywords[NUM_KEYWORDS][MAX_KEYWORD_LEN] = {"happy", "sad", "love", "angry", "excited", "tired"};
char emoticons[NUM_KEYWORDS][MAX_EMOTICON_LEN] = {":-)", ":-((", "<3", ">:(", ":-D", ":-|"};
void replaceKeywordsWithEmoticons(char *input, char *output) {
// Initialize the random number generator
srand(time(NULL));
int inputLen = strlen(input);
int outputLen = 0;
int i = 0;
while (i < inputLen) {
int keywordFound = 0;
int j = 0;
// Check if a keyword is found
for (j = 0; j < NUM_KEYWORDS; j++) {
if (strncmp(&input[i], keywords[j], strlen(keywords[j])) == 0) {
// A keyword is found, replace it with a random emoticon
int emoticonIndex = rand() % NUM_KEYWORDS;
strcpy(&output[outputLen], emoticons[emoticonIndex]);
outputLen += strlen(emoticons[emoticonIndex]);
i += strlen(keywords[j]);
keywordFound = 1;
break;
}
}
// If no keyword is found, copy the character as it is
if (!keywordFound) {
output[outputLen] = input[i];
outputLen++;
i++;
}
}
// Null terminate the output string
output[outputLen] = '\0';
}
int main() {
char input[1000];
char output[1000];
printf("Please enter your text: ");
fgets(input, sizeof(input), stdin);
replaceKeywordsWithEmoticons(input, output);
printf("Output: %s\n", output);
return 0;
}
追问很好啊,就是如果关键字里有另一个关键字,能否将长一些的替换呢シ