user12711792
user12711792

Reputation:

Extract two string from a string with a space

let's suppose

char nickAndPwd[] = "John 1234";

i want to get nick ="John" and password = "1234".How can I do it?

This is what I did but it seems not to work properly

int main() {  

  char nicknameAndPwd[] = "Alessandro 12345678901";
  char nick[10];
  char pwd[11];

  int nickLength = 10;
  int pwdLength = 11;

  memcpy( nick, &nicknameAndPwd[0], nickLength);
  nick[nickLength] = '\0';

  memcpy(pwd, &nicknameAndPwd[nickLength+1], pwdLength);
  pwd[pwdLength] = '\0';

  printf("%s\n", nick);
  printf("%s\n", pwd);

  return 0;
}

How can I fix it?

Upvotes: 0

Views: 39

Answers (2)

Chris Tang
Chris Tang

Reputation: 574

Change your code into:

  nick[nickLength-1] = '\0';
  pwd[pwdLength-1] = '\0';

Both nick and pwd are allocated with the range of [0,size-1].

A more general way to split the string with whitespace could be:

#include<string.h>
#include<stdio.h>
int main() {  

  char nicknameAndPwd[50];
  char *p;
  fgets(nicknameAndPwd,50,stdin);
  if (p=strchr(nicknameAndPwd,'\n')) *p='\0';
  p = strchr(nicknameAndPwd,' ');
  char nick[25];
  char *pswd;
  strncpy(nick,nicknameAndPwd,p-nicknameAndPwd);
  pswd = nicknameAndPwd+(p-nicknameAndPwd)+1;
  puts(nick);
  puts(pswd);
}

Upvotes: 0

prog-fh
prog-fh

Reputation: 16925

If you don't know exactly the length of the name and the password, you should probably try something like this.

/**
  gcc -std=c99 -o prog_c prog_c.c \
      -pedantic -Wall -Wextra -Wconversion \
      -Wc++-compat -Wwrite-strings -Wold-style-definition -Wvla \
      -g -O0 -UNDEBUG -fsanitize=address,undefined
**/

#include <stdio.h>

void
test_function(const char *nicknameAndPwd)
{
  printf("testing with <%s>\n", nicknameAndPwd);
  char nick[11]; // assume no more than 10 useful chars
  char pwd[12]; // assume no more than 11 useful chars
  if(sscanf(nicknameAndPwd, "%10s %11s", nick, pwd)==2)
  {
    nick[10]='\0'; // ensure string termination if input was too long
    pwd[11]='\0'; // ensure string termination if input was too long
    printf("  nick <%s>\n", nick);
    printf("  pwd <%s>\n", pwd);
  }
}

int
main(void)
{
  test_function("Alessandro 12345678901");
  test_function("Shorter 1234567");
  test_function("NowItIsLonger 1234567");
  return 0;
}

Upvotes: 1

Related Questions