c语言实现char replaceCstrconst char allStr const char searchStr const char replaceStr bool isCaseSensitive=true这个函数实现字符串替换给出最高效算法
以下是一个可能的实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
char* replaceCstr(const char* allStr, const char* searchStr, const char* replaceStr, bool isCaseSensitive) {
if (allStr == NULL || searchStr == NULL || replaceStr == NULL) {
return NULL;
}
int allLen = strlen(allStr);
int searchLen = strlen(searchStr);
int replaceLen = strlen(replaceStr);
int count = 0;
const char* p = allStr;
while ((p = strstr(p, searchStr)) != NULL) {
count++;
p += searchLen;
}
int newLen = allLen + count * (replaceLen - searchLen);
char* newStr = (char*) malloc((newLen + 1) * sizeof(char));
if (newStr == NULL) {
return NULL;
}
int i = 0, j = 0;
while (i < allLen) {
if (isCaseSensitive ? strncmp(allStr + i, searchStr, searchLen) == 0 : strncasecmp(allStr + i, searchStr, searchLen) == 0) {
strncpy(newStr + j, replaceStr, replaceLen);
i += searchLen;
j += replaceLen;
} else {
newStr[j++] = allStr[i++];
}
}
newStr[j] = '\0';
return newStr;
}
该函数首先检查输入参数是否为 NULL,然后计算出替换后的字符串长度,并分配相应的内存。接着,它使用 strstr 函数找到所有要替换的字符串,计算出替换后的字符串长度。最后,它使用 strncpy 函数将替换字符串复制到新字符串中,同时跳过要替换的字符串。如果字符串不需要替换,则将其复制到新字符串中。在复制完成后,将新字符串的末尾设置为 null 终止符,并返回指向新字符串的指针。
该函数的时间复杂度为 O(n),其中 n 是 allStr 的长度。它只需要遍历 allStr 一次,并使用 strstr 和 strncmp 函数进行搜索和比较。因此,它是最高效的算法之一
原文地址: http://www.cveoy.top/t/topic/ftf0 著作权归作者所有。请勿转载和采集!