Trying to split a string in C by a space and use the second word

Viewed 659

I'm making a client-server program using sockets, and I need to client to be able to send a message to the server as a command, for example 'user 3' which connects the user to user 3. So far everything is working but I don't know how to separate the string into its useful parts. I need to first check the command which is 'user' and then check the second word which in this case is '3'.

So far I have only managed to split it using the '\0' delimiter which isn't proving to be all that useful, it only allows me to check is the user has said 'user' or '3'.

char receive[1024];
int read = recv(client_socket, &receive, 1024, 0);
receive[read] = '\0';

if (strcmp(receive, "user") == 0) {
    printf("User has requested chat with....");
}
3 Answers

For your use case you should be using

char *strstr(const char *haystack, const char *needle);

it finds the substring in the provided string.

For example:

char receive[1024];
int read = recv(client_socket, &receive, 1024, 0);
receive[read] = '\0';

if (strstr(receive, "user")) {
    printf("User has requested chat with....");
}

Use strtok function which two parameters one the string and one the delimiter.

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

int main ()
{
  char strtest[] ="- This, a string for testing.";
  char * pchs;
  printf ("Splitting string \"%s\" in token:\n",str);
  pch = strtok (strtest," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

The strtok() function is what exactly you need. It separates the string with the given delimiters, here it is whitespace.

char receive[1024];
int read = recv(client_socket, &receive, 1024, 0);
receive[read] = '\0';
char *token = strtok(receive, " ");  // get the first part

while (token != NULL) {  // while there still have unprocessed parts
    // handle the commands, values, whatever you want
    if (strcmp(receive, "user") == 0) {
        printf("User has requested chat with....");
    }

    token = strtok(NULL, " ");  // get the next part
}
Related