首页 > 解决方案 > 替换 C 中的字符串元素

问题描述

我正在尝试将星号替换为字符串中的某些单词。例如:如果字符串是“一个大巨人让我害怕”,我需要用星号替换“巨人”和“害怕”这两个词。字符串应该是 'A big ***** person ****** me'

这是我的代码

int lengthString(char* str) {
    int i = 0;
    while (str[i] != '\0')
            i++;
    return i;
}

void replace(char* start, int length, char ch) {
     for (int i = 0; i < length; i++)
            start[i] = ch;
}

void redact(char* toRedact, char** dictonary, int dicSize) {
    for (int i = 0; i < dicSize; i++) {
            char* redact = dictonary[i];
            char* lastPos = toRedact;
            char* nextPos = strstr(lastPos, redact);
            while (lastPos != NULL) {
                    if (nextPos == NULL){
                      break;
                    }
                    replace(nextPos, lengthString(redact), '*');
                    lastPos = nextPos + 1;
            }
    }
}

int main() {

   char* test[4];
   char* dictionary[4];
   dictionary[0] = "big";
   dictionary[1] = "giant";
   dictionary[2] = "scared";
   dictionary[3] = "person";

   test[0] = "A giant scared me";
   test[1] = "A big scared me";
   test[2] = "A person scared me";

   for(int i = 0; i < 3; i++) {
     redact(test[i], dictionary, 4);
     printf("%s\n", test[i]);
   }

   return 0;
 }

输出:seg fualt

标签: c

解决方案


推荐阅读