【发布时间】: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。我将在下面更新我的答案。