Friday, October 28, 2022

[FIXED] How to remove blank elements from an array of strings in C?

Issue

I was working on file inputs. I wanted to store each line as a string in array. For example: if the file has lines:

This is line 1.
This is line 2.
This is line 3.

The string should contain:

char str[][] = {"This is line 1.", "This is line 2.", "This is line 3."};

When I was trying out with extra spaces:

This is line 1.


This is line 2.
This is line 3.

The output was in the same format. I want to delete those extra empty lines from my array of sentences, so that the output is same as before. How should I do that?

[EDIT] I am using following loop to enter sentences from file to the array:

while (fgets(str[i], LINE_SIZE, fp) != NULL)
{
    str[i][strlen(str[i]) - 1] = '\0';
    i++;
}

Solution

You should use an intermediate one-dimensional character array in the call of fgets like for example

for ( char line[LINE_SIZE]; fgets( line, LINE_SIZE, fp) != NULL; )
{
    if ( line[0] != '\n' )
    { 
        line[ strcspn( line, "\n" ) ] = '\0';
        strcpy( str[i++], line );
    }
}

If a line can contain blanks you can change the condition of the if statement the following way

for ( char line[LINE_SIZE]; fgets( line, LINE_SIZE, fp) != NULL; )
{
    size_t n = strspn( line, " \t" );

    if ( line[n] != '\n' && line[n] != '\0' )
    { 
        line[ n + strcspn( line + n, "\n" ) ] = '\0';
        strcpy( str[i++], line );
    }
}

In the above code snippet you can substitute this statement

strcpy( str[i++], line );

for this statement if you want that the string would not contain leading spaces.

strcpy( str[i++], line + n );


Answered By - Vlad from Moscow
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.