我想在c中编写一个程序来获取第一个字符串的字符串是“ddabcdd” 并且第二个字符串应该在第一个字符串内,就像字符串编号2是“abc”那么第二个字符串应该被字符串编号1中的第三个字符串替换,就像第三个字符串是“fff”,第一个字符串应该更改为“ddfffdd”!!!!!!
第一个字符串:ddabcdd
第二个字符串:abc
第三个字符串:fff
更改后的第一个字符串:ddfffdd
答案 0 :(得分:1)
您需要查找并替换该单词,以便参考以下程序,
// C program to search and replace
// all occurrences of a word with
// other word.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to replace a string with another
// string
char *replaceWord(const char *s, const char *oldW,
const char *newW)
{
char *result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
// Counting the number of times old word
// occur in the string
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
i = 0;
while (*s)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
result[i++] = *s++;
}
result[i] = '\0';
return result;
}
// Driver Program
int main()
{
char str[] = "ddabcdd";
char c[] = "abc";
char d[] = "fff";
char *result = NULL;
// oldW string
printf("Old string: %sn", str);
result = replaceWord(str, c, d);
printf("New String: %sn", result);
free(result);
return 0;
}
感谢。