c語(yǔ)言字符串replace函數(shù)怎么用

小億
161
2023-12-14 23:56:47

C語(yǔ)言沒有內(nèi)置的字符串replace函數(shù),但可以自己編寫一個(gè)函數(shù)來實(shí)現(xiàn)字符串替換的功能。下面是一個(gè)示例的字符串替換函數(shù)的代碼:

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

void replace(char *str, const char *old, const char *new) {
    char *p = strstr(str, old);  // 在str中查找old的出現(xiàn)位置
    if (p != NULL) {  // 如果找到了
        size_t old_len = strlen(old);
        size_t new_len = strlen(new);
        size_t str_len = strlen(str);
        size_t tail_len = str_len - (p - str) - old_len;  // 原字符串尾部的長(zhǎng)度
        
        if (new_len > old_len) {  // 如果新字符串比舊字符串長(zhǎng)
            memmove(p + new_len, p + old_len, tail_len + 1);  // 將尾部的字符后移
        } else if (new_len < old_len) {  // 如果新字符串比舊字符串短
            memmove(p + new_len, p + old_len, tail_len);  // 將尾部的字符后移
            p[str_len - old_len + new_len] = '\0';  // 將多余的字符截?cái)?/span>
        }
        
        memcpy(p, new, new_len);  // 替換舊字符串為新字符串
        replace(p + new_len, old, new);  // 遞歸查找下一個(gè)匹配位置
    }
}

int main() {
    char str[100] = "hello world, world";
    const char *old = "world";
    const char *new = "C";

    printf("原字符串:%s\n", str);
    replace(str, old, new);
    printf("替換后的字符串:%s\n", str);
    
    return 0;
}

上述代碼中的replace函數(shù)實(shí)現(xiàn)了在字符串str中將所有出現(xiàn)的old字符串替換為new字符串的功能。在主函數(shù)中,我們使用replace函數(shù)將字符串中的"world"替換為"C",并輸出替換后的結(jié)果。

注意:上述代碼是一種簡(jiǎn)單的實(shí)現(xiàn)方式,可能無法處理一些特殊情況,例如如果new字符串中包含old字符串時(shí),可能會(huì)出現(xiàn)錯(cuò)誤的結(jié)果。為了處理更復(fù)雜的字符串替換需求,可以使用正則表達(dá)式或者一些現(xiàn)成的字符串處理庫(kù)。

0