0

嗨,对于我的应用程序,我需要删除 char 数组 evry X 字节上的空字节,例如:

char a[] = "\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x0B8\x00\x0B8\x0B8\x0B8\x00\x00"

需要

char a[] = "\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8\xB8";

我需要一个没有 std 的函数,只是 WINAPI 谢谢

4

2 回答 2

2

@Jerry Coffin 描述了这种一般类型问题的惯用解决方案。

您需要就地扫描和修改数组,从左到右扫描,在进行时保留或删除元素,同时跟踪源(输入)索引和目标(输出)索引。由于这会扫描数组的每个元素一次,因此它是一个 O( n ) 算法。

例如:

// Remove all '\x00' elements from an array
int remove_zeros(char a[], int len)
{
    int  si;   // Source index
    int  di;   // Destination index

    // Scan the array from left to right, removing '\x00' elements
    di = 0;
    for (si = 0;  si < len;  si++)
    {
        if (a[si] != '\x00')
            a[di++] = a[si];    // Keep/move the element
        // Otherwise skip/remove the element
    }

    return di;   // Resulting length of the modified array
}

随着循环的进行,di索引保证不大于。si可以将if条件修改为保留数组中元素所需的任何条件。

注意:为了完全迂腐,索引和长度应该是 type size_t,以便可以处理任何大小的数组。我过去int只是为了保持简单。

于 2013-05-24T15:27:47.620 回答
1

一种明显的方法是从头到尾遍历数组,跟踪两个点:“输入”和“输出”。两者的开头相同(数组的开头),但是每次遇到结果中不需要的字节时,都会将输入移动到下一个字节,但不处理输出。当你遇到一个你想保留的字节时,你会从输入点复制到输出点,然后更新它们以指向下一个字节。

于 2013-05-24T14:41:22.680 回答