不明白为什么这个修剪功能不能正常工作
=================================================== ===================================================
void trim(const char * orig, char * dest)
{
size_t front = 0;
size_t end = sizeof(orig) - 1;
size_t counter = 0;
char * tmp = null;
if (sizeof(orig) > 0)
{
memset(dest, '\0', sizeof(dest));
/* Find the first non-space character */
while (isspace(orig[front]))
{
front++;
}
/* Find the last non-space character */
while (isspace(orig[end]))
{
end--;
}
tmp = strndup(orig + front, end - front + 1);
strncpy(dest, tmp, sizeof(dest) - 1);
free(tmp); //strndup automatically malloc space
}
}
=================================================== ========
我有一个字符串:
' ABCDEF/G01 '
上面的函数应该删除空格并返回给我:
'ABCDEF/G01'。
相反,我得到的结果是:
'ABCDEF/'
有什么想法吗?
注意:引号只是为了告诉您原始字符串中存在空格。
===============================================================================
void trim(const char * orig, char * dest)
{
size_t front = 0;
size_t end = sizeof(orig) - 1;
size_t counter = 0;
char * tmp = null;
if (sizeof(orig) > 0)
{
memset(dest, '\0', sizeof(dest));
/* Find the first non-space character */
while (isspace(orig[front]))
{
front++;
}
/* Find the last non-space character */
while (isspace(orig[end]))
{
end--;
}
tmp = strndup(orig + front, end - front + 1);
strncpy(dest, tmp, sizeof(dest) - 1);
free(tmp); //strndup automatically malloc space
}
}
===============================================================================
I have a string:
' ABCDEF/G01 '
The above function is supposed to remove the spaces and return to me:
'ABCDEF/G01'.
Instead, what I get back is:
'ABCDEF/'
Any ideas?
Note: the quotes are just to show you that spaces exist in the original string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
strncpy
是错误的。sizeof(dest)
不是您想要的(它是您机器上指针的大小)。您可能需要:end - front
。相反,请尝试:The
strncpy
is wrong.sizeof(dest)
is not what you want (it's the size of a pointer on your machine). You probably want:end - front
. Instead, try:sizeof(dest)
并没有像你想象的那样做!它返回指针的大小,而不是字符串的长度。您需要为您的函数提供目的地的最大长度。对于字符串
orig
,您要使用strlen
函数。The
sizeof(dest)
doesn't do what you think it does! It returns the size of the pointer, not the length of the string. You need to supply a maximum length of the destination to your function.For the string
orig
you want to use thestrlen
function.您可能需要 strlen 而不是 sizeof 。
You probably want strlen instead of sizeof here.
在该代码中,sizeof(orig) 是指针的大小。所有指针的大小都相同,在您的实现中可能是 8。您想使用的是
strlen(orig)
。In that code,
sizeof(orig)
is the size of a pointer. All pointers are the same size, probably 8 in your implementation. What you want to use isstrlen(orig)
instead.尝试此代码(它不使用临时内存):
注意:未经测试!
Try this code (it doesn't use temporary memory):
NOTE: Not tested!
您必须在函数中的所有位置将 sizeof() 替换为 strlen()。
这是工作编辑:(
我已经测试过)
You must replace sizeof() to strlen() everywhere in your function.
Here is working edit:
(I've tested it)