Home > front end >  Separate words from a string using space?
Separate words from a string using space?

Time:09-22

Input a string from user and separate the words using space. Why is strstr not returning a proper pos?

char array[1024][1024];
char str[100];
printf( "Enter the string ");
fgets(str, 100, stdin);
char str2 = ' ';
int i =0;
int k =0;
while( str[i] != '\0')
{
    int pos = strstr(str, str2);
    if( pos != NULL)
    {
        for( int m = 0; m<pos;m  )
        array[k][m] = str[m];
        pos =0;
        i  ;
        str pos; 
    }
}

CodePudding user response:

Why is strstr not returning a proper pos?

I assume that "proper pos" means position, i.e. the index where the substring was found.

Well, first you call the function incorrect. You pass the character ' ' but the function expects a string like " ".

BUT

Even if you call it correct, strstr never returns a position (aka an index). It returns a pointer

So you can't do stuff like:

for( int m = 0; m<pos;m  )

Read more here:

https://man7.org/linux/man-pages/man3/strstr.3.html

CodePudding user response:

This will separate the words and store in an array, using pointers.

    printwords()
    {
        char array[1024][1024];
        char str[100];
        printf( "Enter the string ");
        fgets(str, 100, stdin);
        int i =0;
        int k =0;
        int r,c =0;
        while( str[i] != '\0')
        {
            if( str[i] != ' ')
            {
                array[r][c  ] = str[i];
                i  ;
            }
            else
            {
                array[r][c] = '\0';
                r  ;
                c=0;
                i  ;
            }      
        }
        for( int m =0; m <= r;m  )
        printf( "Finally %s", array[m]);
    }

CodePudding user response:

"Why is strstr not returning a proper pos?"

char *strstr(const char *str1, const char *str2) requires 2 string arguments, and returns a pointer to the first occurrence of str2. Your code attempts to capture its return value into an int, and attempts to use a char in argument 2. This should have resulted in a compile warning.

But if your intent is to break a string up based on a delimiter such a a space character ( ' ' ), there are better options then using strstr(). As mentioned in the comments ( "have a look at strchr or even strtok... ), take a look at this alternative method using strtok():

char array[1024][1024] = {{0}};//initialize all element of 2D array to zero
char inputBuf[80] = {0};//initialize all array elements to zero.
char *tok = NULL;//initialize pointer to NULL
char delimiter[] = " \n";//set delimiter to contain both space and newline
int index = 0;


printf("%s", "Enter a sentence and hit return.");
if(fgets(inputBuf, sizeof inputBuf, stdin))
{
    tok = strtok (inputBuf, delimiter);
    while(tok)
    {
        strcpy(array[index], tok);
        tok = strtok(NULL, delimiter);
        index  ;
    }
}
  •  Tags:  
  • c
  • Related