簡體   English   中英

用C中的字符串替換字符串中的字符

[英]Replace a character in a string with a string in C

讓下面的示例代碼:

char s1[] = "Hey there #!";
char s2[] = "Lou";

我想編寫一個函數,將s2的值替換為 它還為具有新替換版本的新輸出字符串動態分配內存。 使用大多數內置函數是否可能以一種優雅而簡單的方式? 我知道如何用一個字符串中的一個字符替換一個字符,或者使用給定的子字符串替換一個字符串,但是這似乎讓我很吃驚。

請查看此內容https://stackoverflow.com/a/32496721/5326843根據此,沒有標准函數可以替換字符串。 您必須自己編寫。

您將必須通過幾個功能,但是...這里是:

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

int main()
{
    char s1[] = "Hey there #!";
    char s2[] = "Lou";

    // Get the resulting length: s1, plus s2,
    // plus terminator, minus one replaced character
    // (the last two cancelling each other out).
    char * s3 = malloc( strlen( s1 ) + strlen( s2 ) );

    // The number of characters of s1 that are not "#".
    // This does search for "any character from the second
    // *string*", so "#", not '#'.
    size_t pos = strcspn( s1, "#" );

    // Copy up to '#' from s1
    strncpy( s3, s1, pos );

    // Append s2
    strcat( s3, s2 );

    // Append from s1 after the '#'
    strcat( s3, s1 + pos + 1 );

    // Check result.
    puts( s3 );
}

這並不是您可以做到的那樣高效(尤其是多個strcat()調用效率低下),但是它以最“簡單”的方式僅使用標准函數,並且自身不進行任何“指針”操作。

沒有單個libc調用,但是可以使用多個libc調用,如下所示,無需動態分配。

    #include <stdio.h>
    #include <string.h>
    char* replace_string(char* str, char* find, char* replace_str)
    {
        int len  = strlen(str);
        int len_find = strlen(find), len_replace = strlen(replace_str);
        for (char* ptr = str; ptr = strstr(ptr, find); ++ptr) {
            if (len_find != len_replace) 
                memmove(ptr+len_replace, ptr+len_find,
                    len - (ptr - str) + len_replace);
            memcpy(ptr, replace_str, len_replace);
        }
        return str;
    }

    int main(void)
    {
        char str[] = "Hey there #!";
        char str_replace[] = "Lou";
        printf("%s\n", replace_string(str, "#", str_replace));
        return 0;
    }

輸出:

Hey there Lou!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM