从C中的字符串中获取子字符串

时间:2010-12-14 15:32:50

标签: c arrays substring token

我正在尝试用C编写程序,这将允许我在将要定义的两个其他字符串之间获取我想要的字符串。更具体地说,我的示例字符串是

 "blahblah<mailto:agent007@example.org>blahblahblah"

我需要能够将“agent007”子字符串提取到一个新变量。我已经尝试了strtok()方法,但问题是我无法将标记提取到新变量或数组。我已经对字符串进行了标记,并且可以使我很好的语句就像“如果token [i] ==”mailto“&amp;&amp; token [i + 2] ==”example“那么mailAdd = token [i + 1]“(以伪代码方式:))

我的计划到目前为止

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

int main ()
{
  char str[] ="blahblah<mailto:agent007@example.org>blahblahblah";
  char * tch;
  tch = strtok (str,"<:@");
  while (tch != NULL)
  { 
    printf ("%s\n",tch);
    tch = strtok (NULL, "<:@");
  }
  return 0;
}

当然,除了令牌之外的任何其他建议都将非常感激 -

2 个答案:

答案 0 :(得分:2)

我的第一个想法是将strstr用于“mailto:”并将strchr用于“@”

// pseudo code
char *mailto = strstr(src, "mailto:"); // possibly convert src to lowercase
char *atsign = strchr(mailto, '@');
while (mailto < atsign) *dst++ = *mailto++;

当然这是一个非常粗略的草案。它需要大量的精炼(未能找到“mailto:”字符串或'@'字符,错误检查,特殊情况,测试......)


保存strtok指针

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

int main ()
{
  char str[] ="blahblah<mailto:agent007@example.org>blahblahblah";
  char * tch;
  char * saved;                     /* pmg */
  tch = strtok (str,"<:@");
  while (tch != NULL)
  { 
    int savenext = 0;               /* pmg */
    if (!strcmp(tch, "mailto"))     /* pmg, UNTESTED CODE, need to check case? */
    {                               /* pmg */
      savenext = 1;                 /* pmg */
    }                               /* pmg */
    printf ("%s\n",tch);
    tch = strtok (NULL, "<:@");
    if (savenext == 1)              /* pmg, UNTESTED CODE */
    {                               /* pmg */
      saved = tch;                  /* pmg */
    }                               /* pmg */
  }
  printf ("saved: %s\n", saved);    /* pmg */
  return 0;
}

答案 1 :(得分:1)

您可以使用strstr搜索“mailto:”,然后使用strchr搜索“@”并在中间搜索字符。我从不使用strtok,但我不知道你做了什么有什么问题。

以下是email在您的案例中应指向“agent007”的示例。这里缺少错误处理。这是破坏性的,这意味着它会修改输入字符串,但strtok也是如此。

char *mailto = strstr( str, "mailto:" );
char *at = strchr( mailto, '@' );
char *email = mailto + strlen("mailto:");
*at = '\0';