编程题:从字符数组中删除所有值为x的元素。
发布网友
发布时间:2024-05-06 15:26
我来回答
共3个回答
热心网友
时间:2024-08-04 06:46
int DelCharFrom(char* str, char x)
{
char* tmpstr = NULL, *p;
size_t n = strlen(str);
if ( n <= 0 ) return n;
tmpstr = new char[n + 1];
if ( tmpstr == NULL )
{
return -1;
}
strcpy(tmpstr, str);
p = tmpstr;
n = 0;
while (*p)
{
if ( *p != x)
{
*str = *p;
++str;
++n;
}
++p;
}
*str = '\0';
delete[] tmpstr;
return n;
}
int main(void)
{
char str[100];
strcpy(str, "iMyi iiiiteisti.i");
if ( DelCharFrom(str, 'i') < 0 )
{
cout << "Error.."<< endl;
} else {
cout << str << endl;
}
}
热心网友
时间:2024-08-04 06:44
void DelChar(char * pc,const char x)
{
char * tempc=(char *)pc;
while(*tempc)
{
if(x==*tempc)
{
char * c=tempc;
while(*c)
{
*c=*(c+1);
c++;
}
}
tempc++;
}
}
pc为字符数组,x为你想要删除的字符
热心网友
时间:2024-08-04 06:45
简单,稳定
void del_char(char *str, char x)
{
int i,j;
if(NULL == str){
return ;
}
for(i=0,j=0; '\0'!=str[i]; i++){
if(x != str[i]){
str[j++] = str[i];
}
}
str[j] = '\0';
}