【问题标题】:Extract two string from a string with a space从带有空格的字符串中提取两个字符串
【发布时间】:2020-03-01 12:33:40
【问题描述】:

假设

char nickAndPwd[] = "John 1234";

我想得到nick ="John"password = "1234"。我该怎么做?

这是我做的,但它似乎不能正常工作

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;
}

我该如何解决?

【问题讨论】:

  • nick[nickLength] = '\0' 会写出越界! 数组的大小不是顶部索引,而是元素的数量。因此,当您将nick 定义为10 元素的数组时,这意味着有效索引是09(包括)。
  • 按照上述说明修复错误后,您可以执行 memset(nick, 0, sizeof(nick)) 将其清除。或者,如果你不想使用 memcpy,你可以使用“c”函数 strtok(),它在 string.h
  • 甚至不需要复制,只需用strtok 或等价物分配一个指针。

标签: c string substring


【解决方案1】:

如果您不知道确切名称和密码的长度, 你应该试试这样的。

/**
  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;
}

【讨论】:

    【解决方案2】:

    将您的代码更改为:

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

    nickpwd 都分配了[0,size-1] 的范围。

    用空格分割字符串的更一般的方法是:

    #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);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多