我已经创建了两个函数来查找子字符串索引并替换字符串中的子字符串。我很高兴我陪审团完全操纵了这一点,因为先前提出的类似问题在没有任何帮助的情况下从未被回答/标记为关闭。但是有关更清洁方法的任何建议吗?
void destroy_substr(int index, int len)
{
int i;
for (i = index; i < len; i++)
{
string[i] = '~';
}
}
void find_substr_index(char* substr)
{
int i;
int j;
int k;
int count;
int len = strlen(substr);
for (i = 0; i < strlen(string); i++)
{
if (string[i] == substr[0])
{
for(j = i, k = 0; k < len; j++, k++)
{
if (string[j] == substr[k])
{
count++;
}
if (count == len)
destroy_substr((j - len + 1), len);
}
j = 0;
k = 0;
count = 0;
}
}
}
答案 0 :(得分:2)
您的代码似乎正在尝试重新发明自己的轮子。
通过使用标准C函数strstr()和memset(),您可以获得与预期相同的结果。
#include <stdio.h>
#include <string.h>
char string[] = "foobar foobar foobar";
char substr[] = "foo";
char replace = '~';
int main() {
int substr_size = strlen(substr);
// make a copy to your `string` pointer
// this is to ensure we can safely modify this pointer value, without 'touching' the original one
char *ptr = string;
// while true (infinite loop)
while(1) {
// find pointer to next substring
ptr = strstr(ptr, substr);
// if no substring found, then break from loop
if(ptr == NULL) { break; }
// if found, then replace it with your char
memset(ptr, replace, substr_size);
// increment our string pointer, pass replaced substring
ptr += substr_size;
}
printf("%s\n", string);
return 0;
}
答案 1 :(得分:0)
这个怎么样:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char string[] = "HELLO hello WORLD world HELLO hello ell";
char substring[] = "ell";
int stringLength = strlen(string);
int substringLength = strlen(substring);
printf("Before: %s\n", string);
if(substringLength <= stringLength)
{
int i;
int j;
for(i = 0, j = stringLength - substringLength + 1; i < j; )
{
if(memcmp(&string[i], substring, substringLength) == 0)
{
memset(&string[i], '~', substringLength);
i += substringLength;
}
else
{
i++;
}
}
}
printf("After: %s\n", string);
return 0;
}
主要观点是:
答案 2 :(得分:0)
您可以复制新字符串。如果要支持插入更长的字符串,则需要使用malloc()/ realloc()来管理内存。如果要支持插入较小的字符串,则需要将指针提前到替换字符串的长度,将字符串的其余部分复制到该新位置,然后将字符串的新结尾归零。
#include <stdio.h>
#include <string.h>
#include <err.h>
int main(int argc, char **argv)
{
char *str = strdup("The fox jumps the dog\n");
char *search = "fox";
char *replace = "cat";
size_t replace_len = strlen(replace);
char *begin = strstr(str, search);
if (begin == NULL)
errx(1, "substring not found");
if (strlen(begin) < replace_len)
errx(1, "replacement too long");
printf("%s", str);
memcpy(begin, replace, replace_len);
printf("%s", str);
return 0;
}