c语言 删除字符串中所有空格

c语言 删除字符串中所有空格

第1个回答  2013-08-28
\\删除字符串中的空格void myremovespace(char * str){ char *p1, *p2; char ch; p1 = str; //first pointer p2 = str; // second pointer to the remaining string if (p1==NULL) return; while (*p1) { if (*p1 != ' ') { ch = *p1; *p2 = ch; p1++; p2++; } else { p1++; } } *p2 = '\0';}int main(void) { char * str = "ab c dd e "; char * str1; str1 = (char*)malloc(20); strcpy(str1,str); char str2[]=" a bv cd "; myremovespace(str1); //work myremovespace(str2); //work myremovespace(str); // not work // because str is in a read-only memory. //*p2 = ch will result in run-time error}文章出处:DIY部落( http://www.diybl.com/course/3_program/c++/cppjs/20090403/163811.html)
第2个回答  2013-08-28
void myremovespace(char * str)
{
char *p1, *p2;
char ch;
p1 = str; //first pointer
p2 = str; // second pointer to the remaining string
if (p1==NULL) return;
while (*p1)
{
if (*p1 != ' ')
{
ch = *p1;
*p2 = ch;
p1++;
p2++;
}
else
{
p1++;
}
}
*p2 = '\0';
}
int main(void)
{
char * str = "ab c dd e ";
char * str1;
str1 = (char*)malloc(20);
strcpy(str1,str);
char str2[]=" a bv cd ";
myremovespace(str1); //work
myremovespace(str2); //work
myremovespace(str); // not work
// because str is in a read-only memory.
//*p2 = ch will result in run-time error
}