gpt4 book ai didi

c - 如何放置一个字符串而不是另一个字符串

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

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

4年前关闭。




Improve this question




我想用c编写一个程序,它得到一个字符串,比如第一个字符串是“ddabcdd”
并且第二个字符串应该在第一个字符串中,例如字符串 2 是 "abc"然后第二个字符串应该替换为字符串 1 中的第三个字符串,例如第三个字符串是 "fff",第一个字符串应该更改为“ddffdd”!!!!!!

第一个字符串:ddabcdd

第二个字符串:abc

第三个字符串:fff

更改后的第一个字符串:ddfffdd

最佳答案

您需要找到并替换单词,以便引用以下程序,

// 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;

}

谢谢。

关于c - 如何放置一个字符串而不是另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47375021/

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