gpt4 book ai didi

c - 替换字符串中的子字符串 - c

转载 作者:行者123 更新时间:2023-11-30 20:39:06 26 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序在字符串中查找子字符串并将其替换为用户输入的另一个子字符串。我的代码没有给出编译或运行时错误,但它就是不起作用。我将 printfs 放入 while 循环中,并在其附近写了一条注释行,并且如果 -我在其附近放置了另一条注释行,则程序不会首先进入。它打印 a、h 和 i。循环中的其他部分不起作用。这是我的代码:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

char *findAndReplace(char *sentence, char *word1, char *word2);

void main()
{
char sentence[1000];
char word1[200];
char word2[200];
int length;

printf("Please enter a sentence: ");
gets(sentence);

printf("Please write the word to be replaced: ");
gets(word1);

printf("Please write the word to be put instead: ");
gets(word2);

findAndReplace(sentence, word1, word2);

system("pause");


}

char* findAndReplace(char *sentence, char *word1, char *word2)
{
char *search, *tempString[1000];
int a, b, c, d, i = 0, j, sentenceLength, word1Length, searchLength;

sentenceLength = strlen(sentence);
printf("Length of %s is %d\n", sentence, sentenceLength);

printf("Finding ");
puts(word1);

search = strstr(sentence, word1);
searchLength = strlen(search);
word1Length = strlen(word1);

strcpy(tempString, sentence);

if(search != NULL)
{
printf("Starting point: %d\n", sentenceLength - searchLength);
}
else
{
printf("Eşleşme bulunamadı.\n");
}
j = 0;
while(j < sentenceLength + 1) //This loop
{
printf("a");
if(word1[i] == tempString[j])
{
printf("b");

if(i == word1Length)
{
c = j;
printf("c");

for(d = 0; d < word1Length; d++)
{
tempString[c - word1Length + d + 1] = word2[d];
printf("d");
}

i = 0;
j++;
printf("e");
}

else
{ printf("f");
i++;
j++;
}
printf("g");
}

else{
printf("h");
i = 0;
j++;
}
printf("i");
}
puts(tempString);
}

最佳答案

你已经有了一个不错的开始,但你却让事情变得比需要的困难得多。最小化错误的一种方法是在标准库函数可以完成您需要完成的工作时依赖标准库函数。例如:

char tempString[1000];
char *search;

search = strstr(sentence, word1);
if (search) {
ptrdiff_t head_length = search - sentence;
int sentence_length = strlen(sentence);
int word1_length = strlen(word1);
int word2_length = strlen(word2);

if (sentence_length + word2_length - word1_length < 1000) {
/* construct the modified string */
strncpy(tempString, sentence, head_length);
strcpy(tempString + head_length, word2);
strcpy(tempString + head_length + word2_length, search + word1_length);
/* copy it over the original (hope it doesn't overflow!) */
strcpy(sentence, tempString);
} else {
/* oops! insufficient temp space */
}
} /* else the target word was not found */

这仅涵盖搜索/替换位,修复了 iharob 首先指出的 tempString 类型中的错误。此外,它仅替换第一次出现的目标单词,正如原始代码似乎试图做的那样。

关于c - 替换字符串中的子字符串 - c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com