【问题标题】:get substring from string in C从C中的字符串获取子字符串
【发布时间】:2011-05-25 08:35:18
【问题描述】:

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

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

我需要能够将“agent007”子字符串提取到一个新变量中。我尝试了 strtok() 方法,但问题是我无法将标记提取到新变量或数组中。我已经对字符串进行了标记,适合我的语句将类似于 " if token[i] == "mailto" && token[i+2] == "example" then 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;
}

当然,除了代币之外的任何其他建议将不胜感激 -

【问题讨论】:

  • 令牌对我来说似乎是合理的。我不清楚你遇到了什么问题。为什么不能提取令牌?
  • 你好乔纳森。我似乎找不到将令牌导出到 char var 并稍后在程序中用于其他计算的方法。我说得有道理吗? :)
  • 如果你想重用它,你需要将tch字符串复制到某个地方:tch本身不断变化。请注意,strtok 更改了原始字符串。在你的循环之后,(如果我没有搞砸计算)str+0 指向“blahblah”; str+9 指向“mailto”; str+16 指向“agent007”;和str+25 指向“example.org>blahblahblah”。
  • @pmg:感谢您的回复。但这里有一个棘手的问题:在事先不知道字符串长度的情况下,我如何才能获得“agent007”令牌? :)
  • 您只需要保存指针,@Sakis。我将在下面更新我的答案。

标签: c arrays substring token


【解决方案1】:

我的第一个想法是使用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;
}

【讨论】:

  • 好吧,我明白你在那里做了什么 :) 经过测试,工作起来就像一个魅力。感谢无数pmg :)
【解决方案2】:

您可以使用strstr 搜索“mailto:”,然后使用strchr 搜索“@”并获取中间的字符。我从不使用strtok,但我看不出你所做的有什么问题。

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

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

【讨论】:

  • 这就是我面临的问题。 :) 我怎样才能得到这些字符?
猜你喜欢
  • 2012-01-26
  • 1970-01-01
  • 2011-12-27
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多