2013-02-23 68 views
0

說我有一個這樣的字符串:aaaaaa利用子轉換規則轉換字符串

而且我有一個需要被應用,看起來像這樣一個轉變:aa -> b

我的問題是:

  1. 我將如何找到所有子字符串(分別)是將轉換規則應用於給定字符串中的每個子字符串的結果。因此,舉例來說,在我把作爲一個例子的情況下,我需要得到以下結果字符串:

    baaaa, abaaa, aabaa, aaaba, AAAAB

+0

如果您有兩個問題,則應將它們作爲單獨問題發佈。 – thejh 2013-02-23 09:58:59

+0

thejh完成。抱歉。 – 2013-02-23 09:59:33

+0

呃...你不想一次申請所有比賽的轉換,但是你想要所有比賽的單獨結果字符串? – thejh 2013-02-23 10:16:23

回答

1

步驟通過增加char *來通過字符串。每次你在字符串中前進一步,用strncmp檢查是否需要的子字符串(例如aa)跟在後面。每次都是這樣,複製字符串並替換副本中要查找的字符串:

// str is the string 
// needle is what you want to replace 
// replacement is what you want to replace the needle with 
for (char *p = str; *p != '\0'; p++) { 
    if (strncmp(p, needle, strlen(needle)) == 0) { 
    char *str_ = malloc(strlen(str)+1+strlen(replacement)-strlen(needle)); 
    strcpy(str_, str); 
    char *p_ = p - str + str_; 
    memmove(p_+strlen(replacement), p_+strlen(needle), strlen(p_)+1-strlen(replacement)); 
    memcpy(p_, replacement, strlen(replacement)); 
    // do something with str_ here (and probably free it at some point) 
    } 
} 
+0

你是一位天才。非常感謝你。 – 2013-02-23 14:34:29