第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在C中替換字符串的函數(shù)是什么?

在C中替換字符串的函數(shù)是什么?

C
紅顏莎娜 2019-08-03 03:03:54
在C中替換字符串的函數(shù)是什么?給定一個(char*)字符串,我希望找到一個子字符串的所有匹配項,并將其替換為一個備用字符串。我沒有看到任何簡單的函數(shù)可以在<string.h>中實現(xiàn)這一點。
查看完整描述

3 回答

?
三國紛爭

TA貢獻1804條經(jīng)驗 獲得超7個贊

優(yōu)化器應(yīng)該消除大多數(shù)局部變量。tmp指針的存在是為了確保strcpy不必遍歷字符串才能找到空值。TMP指向每次呼叫后的結(jié)果結(jié)束。(見畫家的算法為什么strcpy會很煩人。)

// You must free the result if result is non-NULL.char *str_replace(char *orig, char *rep, char *with) {
    char *result; // the return string
    char *ins;    // the next insert point
    char *tmp;    // varies
    int len_rep;  // length of rep (the string to remove)
    int len_with; // length of with (the string to replace rep with)
    int len_front; // distance between rep and end of last rep
    int count;    // number of replacements

    // sanity checks and initialization
    if (!orig || !rep)
        return NULL;
    len_rep = strlen(rep);
    if (len_rep == 0)
        return NULL; // empty rep causes infinite loop during count
    if (!with)
        with = "";
    len_with = strlen(with);

    // count the number of replacements needed
    ins = orig;
    for (count = 0; tmp = strstr(ins, rep); ++count) {
        ins = tmp + len_rep;
    }

    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);

    if (!result)
        return NULL;

    // first time through the loop, all the variable are set correctly
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    while (count--) {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;}




查看完整回答
反對 回復(fù) 2019-08-04
?
明月笑刀無情

TA貢獻1828條經(jīng)驗 獲得超4個贊

這在標準C庫中沒有提供,因為只要給定一個char*,如果替換字符串的長度大于要替換的字符串,則不能增加分配給該字符串的內(nèi)存。

您可以更容易地使用std:string來完成這一任務(wù),但是即使在那里,也不會有單個函數(shù)為您完成此操作。


查看完整回答
反對 回復(fù) 2019-08-04
?
慕絲7291255

TA貢獻1859條經(jīng)驗 獲得超6個贊


由于C中的字符串不能動態(tài)增長,所以內(nèi)部替換通常不起作用。因此,您需要為有足夠空間進行替換的新字符串分配空間,然后將部分從原始字符串再加上替換復(fù)制到新字符串中。復(fù)制要使用的部件斯特恩.


查看完整回答
反對 回復(fù) 2019-08-04
  • 3 回答
  • 0 關(guān)注
  • 433 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號