// 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 条件可以修改为在数组中保留元素所需的任何条件。
注意:为了完全迂腐,索引和长度应为 size_t 类型,以便可以处理任何大小的数组。我使用 int 只是为了让事情变得简单。