繁体   English   中英

[代码演练]如何从C中的字符串中删除所有出现的给定字符?

[英][Code Walkthrough]How to remove all occurrences of a given character from string in C?

阅读此处最佳答案的代码后,
我有几个问题为什么这个答案成功地发挥了应有的作用。
我已经亲自浏览了这段代码,但仍然不知道为什么str能够获得预期的字符串。
我没有足够的声誉对这个答案发表评论,所以我决定提出一个新问题。

以下是@dasblinkenlight提供的代码。 (出于测试目的,我更改了输入string 。)

void remove_all_chars(char* str, char c) {
    char *pr = str, *pw = str;           // line 1
                                         // Inside the while loop
    while (*pr) {                        // line 3
        *pw = *pr++;                     // line 4
        pw += (*pw != c);                // line 5
        printf("str: %s\n", str);       // FYI, this will always print `abcd`, isn't it weird, if `str` is mutated in the end of this program?
    }
    *pw = '\0';
}

int main() {
    char str[] = "abcd";
    remove_all_chars(str, 'c');
    printf("'%s'\n", str);
    return 0;
}

所以,据我所知,这是代码的演练。

line 1中, *pr*pw都指向输入string的第一个元素
*pr ==> 'a'
*pw ==> 'a'

while循环内。
结果将由|分隔每次迭代。
(第 1 次迭代) (第 2 次迭代) (第 3 次迭代) (第 4 次迭代)
*pr (第 3 行)========> 'a' | 'b' | 'c' | 'd'
*pw = *pr++ (第 4 行)==> 'a' = 'b' | 'b' = 'c' | 'c' = 'd' | 'c' = '\0'
(*pw != c) (第 5 行) ==> 'b' != 'c' (true)| 'c' != 'c' (假)| 'd' != 'c' (真) | '\0' != 'c' (真)
pw (之后, pw += (*pw != c) ) ==> str[1] , 'b' | str[1] , 'c' | str[2] , 'c' | str[3] , 'd'

所以现在,如果我的演练是正确的,我应该有str ,其值为bd
但是,在代码编辑器上运行它,它会给我返回预期的答案abd

我用编辑器仔细检查了我的演练,所以我很确定每个变量中值的变化。
如果您可以帮助理解为什么strabd的值结尾,请告诉我。

提示您的是第 4 行。您可以将此行视为两行:

新行 4: *pw = *pr;

新的第 5 行:pr++;

这意味着当 pw 指向“a”时,它将被 pr 当前指向的“a”覆盖,而不是“b”。 在您的演练中,您有 'a' = 'b'。 正确的版本是 'a' = 'a' 然后 pr 前进到 'b'。 用我提供的两行代码做一个演练,你会更好地理解它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM