D语言转C语言:字符串替换函数的实现和性能对比
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <time.h>
// 判断两个字符是否相等,根据 isCaseSensitive 参数决定是否区分大小写 int charEqual(char a, char b, int isCaseSensitive) { if (isCaseSensitive) { return a == b; } else { return tolower(a) == tolower(b); } }
// 在字符串 haystack 中查找第一次出现 needle 的位置,返回指向该位置的指针,如果找不到则返回 null char* strstrCase(char* haystack, const char* needle, int isCaseSensitive) { if (!haystack || !needle || !*needle) { return haystack; }
size_t haystackLen = strlen(haystack);
size_t needleLen = strlen(needle);
if (needleLen > haystackLen)
{
return NULL;
}
if (isCaseSensitive)
{
return strstr(haystack, needle);
}
for (size_t i = 0; i <= haystackLen - needleLen; i++)
{
int found = 1;
for (size_t j = 0; j < needleLen; j++)
{
if (!charEqual(haystack[i + j], needle[j], isCaseSensitive))
{
found = 0;
break;
}
}
if (found)
{
return haystack + i;
}
}
return NULL;
}
char* replaceCstr(const char* allStr, const char* searchStr, const char* replaceStr, int isCaseSensitive) { if (!allStr || !searchStr || !replaceStr || !searchStr) { return (char)allStr; }
char* result = NULL;
size_t searchStrLength = strlen(searchStr);
size_t replaceStrLength = strlen(replaceStr);
size_t count = 0;
char* p = (char*)allStr;
while ((p = strstrCase(p, searchStr, isCaseSensitive)) != NULL)
{
count++;
p += searchStrLength;
}
if (count == 0)
{
return (char*)allStr;
}
size_t newStrLength = strlen(allStr) + count * (replaceStrLength - searchStrLength);
result = (char*) malloc(newStrLength + 1);
char* q = result;
p = (char*)allStr;
while (count-- > 0)
{
char* r = strstrCase(p, searchStr, isCaseSensitive);
long length = r - p;
memmove(q, p, length);
q += length;
memcpy(q, replaceStr, replaceStrLength);
q += replaceStrLength;
p = r + searchStrLength;
}
strcpy(q, p);
return result;
}
int main() { clock_t start = clock();
char str[] = "hello, world!";
const char* oldptr = str;
char* now = NULL;
for (int ii = 0; ii < 10000000; ii++)
{
now = replaceCstr(oldptr,"o","O",1);
free(now);
now = replaceCstr(oldptr,"l","1",1);
free(now);
now = replaceCstr(oldptr,",","",1);
free(now);
now = replaceCstr(oldptr,"!","",1);
free(now);
//str = str.replaceString("o", "0").replaceString("l", "1").replaceString(",", "").replaceString("!", "");
}
clock_t end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("C语言程序运行时间 :%f\n", time_spent);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/ohVv 著作权归作者所有。请勿转载和采集!