3

==================================================== ==============================

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/'

有任何想法吗?

注意:引号只是为了告诉您原始字符串中存在空格。

4

6 回答 6

4

strncpy是错的。sizeof(dest)不是你想要的(它是你机器上指针的大小)。你可能想要:end - front. 相反,请尝试:

memcpy(dest, front + start, end - front);
dest[end] = 0;
于 2011-11-11T15:08:36.610 回答
2

sizeof(dest)没有做你认为它做的事!它返回指针的大小,而不是字符串的长度。您需要为函数提供目的地的最大长度。

orig对于要使用strlen函数的字符串。

于 2011-11-11T15:10:37.653 回答
1
size_t end = sizeof(orig) - 1;
strncpy(dest, tmp, sizeof(dest) - 1);

您可能在这里需要 strlen 而不是 sizeof 。

于 2011-11-11T15:08:38.447 回答
1
void trim(const char * orig, char * dest)
{
    size_t front = 0;
    size_t end = sizeof(orig) - 1;

在该代码中,sizeof(orig)是指针的大小。所有指针的大小都相同,在您的实现中可能是 8 个。你想要使用的是strlen(orig)

于 2011-11-11T15:08:48.290 回答
0

试试这个代码(它不使用临时内存):

void trim(const char * orig, char * dest)
{
    size_t front = 0;
    size_t end = strlen(orig)-1;
    size_t counter = 0;

    *dest = '\0';

    if (strlen(orig) > 0)
    {    
        /* Find the first non-space character */
        while (front < end && isspace(orig[front]) )
        {
                front++;
        }
        /* Find the last non-space character */
        while (front < end && isspace(orig[end]))
        {
                end--;
        }

        counter = front;
        while ( counter <= end )
        {
                dest[counter-front] = orig[counter];
                counter++;
        }
    }
}

注意:未经测试!

于 2011-11-11T15:17:23.237 回答
0

您必须在函数中的任何位置将 sizeof() 替换为 strlen()。这是工作编辑:

void trim(const char * orig, char * dest)
{
    size_t front = 0;
    size_t end = strlen(orig)-1;
    size_t counter = 0;
    char * tmp = NULL;

    if (strlen(orig) > 0)
    {
        memset(dest, '\0', strlen(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, strlen(dest));
        free(tmp); //strndup automatically malloc space
    }
}

(我已经测试过了)

于 2011-11-11T15:17:34.660 回答