RE:从C中的数组中删除空行/空字符串

时间:2014-11-03 14:03:44

标签: c arrays string multidimensional-array

关于来自莫斯科的@Vlad代码: copy 2 arrays into 1 array, in C prog

如果以这种方式编辑代码,有人知道如何删除空行:

#include <stdio.h>
#include <string.h>

int main(void) 
{
size_t i;
    char ar1[3][10]={"a","b","c"};
    char ar2[3][10]={"d","e","f"};
    char ar3[10][10];

    memcpy( ar3, ar1, sizeof( ar1 ) );
    memcpy( ar3 + 5, ar2, sizeof( ar2 ) );  

    for (i = 0; i < 10; i++ )
    {
        puts( ar3[i] );
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

这是一个如何完成的例子

#include <stdio.h>
#include <string.h>

size_t remove_blank( char ( *s )[10], size_t n )
{
    size_t i = 0;

    while ( i < n && !( s[i][0] == '\0' ) ) ++i;

    for ( size_t j = i + 1; j < n; j++ )
    {
        if ( s[j][0] != '\0' )
        {
            strcpy( s[i], s[j] );
            ++i;
        }
    }

    for( size_t j = i; j < n; j++ ) s[j][0] = '\0';

    return i;
}

int main(void) 
{
    char ar1[3][10]={"a","b","c"};
    char ar2[3][10]={"d","e","f"};
    char ar3[10][10] = { { '\0' } };;

    size_t j = 0;
    for ( size_t i = 0; i < 3; i++, j++ )
    {
        strcpy( ar3[j], ar1[i] );
    }

    j += 2;

    for ( size_t i = 0; i < 3; i++, j++ )
    {
        strcpy( ar3[j], ar2[i] );
    }

    for ( size_t i = 0; i < 10; i++ )
    {
        puts( ar3[i] );
    }

    size_t n = remove_blank( ar3, 10 );

    for ( size_t i = 0; i < n; i++ )
    {
        puts( ar3[i] );
    }

    return 0;
}

输出

a
b
c


d
e
f


a
b
c
d
e
f

对于复制数组的方法也可以这样做。唯一的要求是ar3应为零初始化

char ar3[10][10] = { { '\0' } };