我有这样的代码:
#include <stdio.h>
#include <string.h>
int main()
{
char buf[255];
char buf2[255];
char myhost[255] = "subdomain.domain.com";
char *pch;
int token_counter = 0;
memset(buf, 0, 255);
memset(buf2, 0, 255);
pch = strtok(myhost, ".");
while (pch != NULL)
{
pch = strtok(NULL, ".");
if (pch == NULL)
{
memset(buf, 0, 255);
strncpy(buf, buf2, strlen(buf2) - 1);
break;
}
token_counter++;
strcat(buf2, pch);
strcat(buf2, ".");
}
printf("Domain: %s\n", buf);
return 0;
}如果我的主机被定义为subdomain.domain.com,这是很好的,但是如果它是domain.com,则显示"com“作为最终结果。
如何使它能够正确地检测它是子域还是域?也许我应该包括一个已知的tlds?的列表
发布于 2013-01-12 12:58:21
strtok过火了,strcat浪费了。如果您只想打印超过nth .的所有内容,请使用strchr或检查字符串来查找nth .。如果愿意,从字符串的末尾计数。
让我解释一下为什么strcat在这里浪费时间。考虑:
const char *name = "foo.bar.baz.qux.net";
printf( "%s\n", name + 8 );如果要打印"baz.qux.net",则不需要将该字符串复制到新缓冲区,因为您已经有了指向所需字符串的第一个字符的指针。用你所拥有的。您所需要做的就是在字符串中找到指向所需.的指针,然后执行printf( "%s\n", dot + 1 )或puts( dot + 1 )。(puts在这里更好,但您可能更熟悉printf)
发布于 2013-01-12 12:56:22
若要确定它是否为子域,请计算主机名中以句点分隔的令牌数。正如上面的评论所指出的那样,这并没有考虑到像foo.on.ca这样的事情。
https://stackoverflow.com/questions/14293487
复制相似问题