[转载]c删除字符串中指定字符

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int del_char(char* src, char c)
{
        if ( NULL == src)
        {
                fprintf(stderr, "del_char failed: invalid input./n");
                return -1;
        }
        char* pchTemp = (char*)malloc(strlen(src) + 1);
        if ( NULL == pchTemp)
        {
                fprintf(stderr, "del_char failed: malloc failed/n");
                return -1;
        }
        int num = 0;
        int i = 0;
        int j = 0;
        while ( src[i] != '/0')
        {
                if ( src[i] != c)
                {
            pchTemp[j++] = src[i++];
                }
                else
                {
                        i++;
                        num++;
                }
        }
        pchTemp[j] = '/0';
        if ( 0 != num)
        {
                strncpy(src, pchTemp, strlen(pchTemp) + 1);
        }
        free(pchTemp);
        return num;
}
int main(int argc, char* argv[])
{
        if ( 3 != argc)
        {
                fprintf(stderr, "Usage: %s [src] [c]/n", argv[0]);
                return -1;
        }
        char szSrc[512] = {0};
        snprintf(szSrc, sizeof(szSrc), "%s", argv[1]);
        char c = argv[2][0];
        int num = 0;
        if ( (num = del_char(szSrc, c)) < 0)
        {
                return -1;
        }
        else
        {
                printf("num: %d after del %c: %s/n", num, c, szSrc);
                return 0;
        }
        return 0;
}
posted @ 2011-09-25 21:51  火腿骑士  阅读(916)  评论(0编辑  收藏  举报