C 中的 Trim 函数,用于就地修剪(不返回字符串)
char testStr[] = " trim this ";
char** pTestStr = &testStr;
trim(pTestStr);
int trim(char** pStr)
{
char* str = *pStr;
while(isspace(*str)) {
(*pStr)++;
str++;
}
if(*str == 0) {
return 0;
}
char *end = str + strlen(str) - 1;
while(end > str && isspace(*end))
end--;
*(end+1) = 0;
return 0;
}
char testStr[] = " trim this ";
char** pTestStr = &testStr;
trim(pTestStr);
int trim(char** pStr)
{
char* str = *pStr;
while(isspace(*str)) {
(*pStr)++;
str++;
}
if(*str == 0) {
return 0;
}
char *end = str + strlen(str) - 1;
while(end > str && isspace(*end))
end--;
*(end+1) = 0;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使
testStr
可写:问题是
char *ptr = ...
有ptr
指向实际的文字字符串,该字符串位于只读存储器。通过使用 char testStr[] = ... ,您可以分配一个数组,并使用与文字字符串相同的内容初始化该数组。由于这是一个数组,因此它是可写的。
You need to make
testStr
writeable:The problem is that
char *ptr = ...
hasptr
pointing to the actual literal string which is in read-only memory.By using
char testStr[] = ...
you are allocating an array and having the array initialized with the same contents as the literal string. Since this is an array, it is writable.编辑:根据最新版本的zString库更新了代码。
下面是我对
trim
、left-trim
和right-trim
函数的实现(将添加到 zString 字符串库)。尽管这些函数返回
*char
,但由于原始字符串被修改,这些将满足您的目的。人们可以使用标准库函数,例如 isspace(),但下面的实现是简单的代码,不依赖于任何库函数。
Edit : updated the code based on the latest version of zString library.
Below is my implementation for
trim
,left-trim
and ,right-trim
functions (will be added to zString string library).Although the functions return
*char
, since the original string is modified, these would serve your purpose.One could use standard library functions, such as
isspace()
, but implementations below are bare bone code, that relies on no library function.