C語言實現刪除一個字符串中的指定字母

題目要求

刪除一個字符串中的指定字母,如:字符串 “hello,world!”,刪除其中的 o 字母,應輸出 “hell,wrld!”

解題思路

將字符串內不屬於需搜索的字符的字符再賦值到該字符串的地址空間中,最後再在字符串結尾加上結束標記\0

程序代碼

#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
    int num = 0;
    for (int i = 0; i <= strlen(argv[1]); i++)
        if (argv[1][i] != argv[2][0])
        {
            argv[1][num] = (i == strlen(argv[1])) ? '\0' : argv[1][i];
            num++;
        }
    printf("%s\n", argv[1]);
    return 0;
}

運行結果

2018-02-22 08-22-51屏幕截圖.png

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha Code