2

I am trying to remove all spaces from a string and add each word into a string array.

For instance, provided the string:

char command[120] = "apple   banana orange  dogfood"

an array, defined as:

char *items[20+1]; //Maximum 20 items in string + 0

would contain the elements:

{"apple", "banana", "orange" "dogfood"}

That is, all spaces have been removed.

My goal is to be able to make the call:

echo    1    3 2

and printing out

1 3 2

instead of

    1    3 2

CODE

So far, I have the following:

    char temp_array[120];
    //Populate array with words
    int i, j = 0, ant = 0;
    for(i = 0; i < strlen(command); i++) {
        if(isspace(command[i]) || command[i] == '\0') {
            if(ant <= 20) {
                temp_array[j] = '\0';
                memo = (char *) malloc(sizeof(temp_array)); //allocate memory
                strcpy(memo, temp_array);
                items[ant] = memo;
                memset(temp_array, 0, j);
                ant++;
                j= 0;
            }
        }
        else if(!isspace(command[i])) {
            temp_array[j] = command[i];
            j++;
        }
    }//Done populating array
    items[ant] = NULL;

Any help is highly appreciated!

5
  • char *items[20+1] is array of 21 string pointers. To define N elements of 20+1 chars, write char items[][20+1]. Commented Nov 4, 2015 at 9:23
  • @i486: The char array should be able to contain a maximum of 20 words (pluss 1), not a maximum of 20 characters. Commented Nov 4, 2015 at 9:25
  • Help with what problem? Commented Nov 4, 2015 at 9:30
  • 1
    Can you outline what part of your code does not seem to work? (I'm only assuming it doesn't.) Must you duplicate the strings, or is it enough to have pointers into command? This mainly depends on where command came from and what its lifetime is through your program. Commented Nov 4, 2015 at 9:37
  • There are library functions that will do this for you. Look up strtok() and strsep(). Commented Nov 4, 2015 at 9:48

4 Answers 4

4

This problem may be solved naturally using strtok.

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

int main()
{
    char str[] = "apple   banana orange  dogfood";
    char *items[20] = { NULL };
    char *pch;

    pch = strtok( str," \t\n" );
    int i = 0;
    while( NULL != pch )
    {
        items[i++] = pch;
        pch = strtok( NULL, " \t\n" );
    }

    for( i = 0; i < 20; i++ )
    {
        if( NULL != items[i] )
        {
            printf( "items[%d] = %s\n", i, items[i] );
        }
        else
        {
            break;
        }
    }
    return 0;
}

Output:

items[0] = apple
items[1] = banana
items[2] = orange
items[3] = dogfood
Sign up to request clarification or add additional context in comments.

1 Comment

Note: the pointers assigned to the items array are only valid so long as the memory containing str remains valid. You will need to provide adequate storage for, and copy, each string pointed to by pch to items (instead of simply assigning the pointer) if for instance you call strtok in a function and return a pointer to items.
0

Loop through each character. If it's a space, continue. If it's not, add the address of that character to the array, loop until the first occurring space and replace it with a null terminator. Repeat.

Note that this destroys your initial string (command in your case). Also remember it must be modifiable (cannot be a read-only string).

Comments

0

Here is a function that identify words in a string and stores them in an array.

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

int GetWords(char *String,char **buffer);

int main(void)
{
    char command[120] = "   apple   banana orange  dogfood";

    char *items[20+1];

    int num_of_words = GetWords(command,items);

    for( int n = 0 ; n < num_of_words ; n++ )
    {
        printf("%s ",items[n]);
        free(items[n]);
    }
    puts("");
    return 0;
}

int GetWords(char *String,char **buffer)
{
    int x = -1 , y = 0 , z = 0 ;

    size_t len = strlen(String) , n ;

    for( n = 0 ; n < len ; n++ )
    {
        y++;

        if( String[n] == ' ' )
        {
            y = 0;
            z = 0;
        }

        if( y == 1 )
        {
            x++;
            buffer[x] = (char*)malloc(len+1);
        }

        if( y > 0 )
        {
            buffer[x][z] = String[n];
            z++;
            buffer[x][z] = '\0';
        }
    }
    //return number of words
    return (x+1);
}

Comments

0
String Current = "hello java example";
String trimstr=Current.trim().replace(" ", "");

int count=trimstr.length();

String tryarray[]=new String[count];
for(int i =0;i<count;i++){
tryarray[i]=trimstr.substring(i, i+1);
System.out.println(trimstr.substring(i, i+1));
}
System.out.println("arrays is "+Arrays.toString(tryarray));

1 Comment

What is String tryarray[]=new String[count]; in this C language post?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.