[转载]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;
}
#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;
}
虽功未成,亦未敢藏私,众侠诸神通尽录于此,竟成一笈,名葵花宝典,以飨后世。
邮箱:steven9801@163.com
QQ: 48039387
邮箱:steven9801@163.com
QQ: 48039387