2013-02-23 66 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