[英]Removing whitespace from string in C using pointer to pointer
我在尝试使用采用双指针参数的方法从字符串(例如:“ab c x”)中删除所有空格时遇到一些问题。 我已经使用单指针和 c++ 中的字符串解决了它,但出于好奇,我也想让它正常工作:)
这是我试过的:
void remove_whitespace(char** s)
{
char **rd; // "read" pointer
char **wr; // "write" pointer
rd = wr = s; // initially, both read and write pointers point to beginning of string
while ( *rd != 0 ) // while not at end of string
{
while ( isspace( **rd ) ) // while rd points to a whitespace character
rd++; // advance rd
*wr++ = *rd++; // copy *rd to *wr, advance both pointers
}
*wr = 0; // terminate the result
printf("\nsquished: %s\n", s);
}
这个 function 中的所有错误都源于混淆了间接级别。 在char*
上使用char**
会增加间接级别,这会影响这些变量的每次使用。
只需将 function 转换为使用char*
即可使其更加清晰:
void remove_whitespace(char* s)
{
char *rd; // "read" pointer
char *wr; // "write" pointer
rd = wr = s; // initially, both read and write pointers point to beginning of string
while ( *rd != 0 ) // while not at end of string
{
if (isspace( *rd ) ) // while rd points to a whitespace character
{
rd++; // advance rd
continue;
}
*wr++ = *rd++; // copy *rd to *wr, advance both pointers
}
*wr = 0; // terminate the result
printf("\nsquished: %s\n", s);
}
char **remove_whitespace(char **s)
{
char *rd; // "read" pointer
char *wr; // "write" pointer
rd = wr = *s;
while ( *rd) // while not at end of string
{
while ( isspace( (unsigned char)*rd ) ) // while rd points to a whitespace character
rd++; // advance rd
*wr++ = *rd++; // copy *rd to *wr, advance both pointers
}
*wr = 0; // terminate the result
printf("\nsquished: %s\n", *s);
return s;
}
用法:
int main(void)
{
char z[] = "asdas das as \r dfds \n dsa \t";
char *p = z;
remove_whitespace(&p);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.