替换C中的String元素

时间:2018-05-03 12:27:20

标签: c

我正在尝试将星号替换为字符串中的某些单词。 例如:如果字符串是'一个巨大的人吓到我',我需要用'巨人'和'害怕'来代替星号。字符串应该是'一个很大的人*****我'

这是我的代码

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

0 个答案:

没有答案