gpt4 book ai didi

c - 迭代 C 中的输入 char 参数?

转载 作者:行者123 更新时间:2023-11-30 19:35:22 25 4
gpt4 key购买 nike

我正在尝试迭代 C 中的输入参数,我将其存储在指向 char 的指针中,如下所示:const char *page = argv[1];

现在参数将是一个 http 地址,因此它可能看起来像这样:

http://host:port/folder1/folder2/file.jpg

我想要的是:解析这个字符串并将其分成子字符串

char host = "host"; 
char port = "port";
char path = "/folder1/folder2/file.jpg";
char file = "file.jpg";

所以我认为一个简单的 for 循环(例如计算斜杠数量)可能会达到目的。

int slash_cnt = 0;
int i = 0;

for (i = 0, page[i] != '\0', i++)
{
if (strcmp(&page[i], "/"))
{
slash_cnt++;
}
}

但这不起作用。

如果有人可以在这里帮助我,或者甚至建议一种更好的方法来解析输入中指定的http地址并将其相应地分开,我将非常感激!

最佳答案

strstr 可用于搜索分隔各部分的字符串 ///:出于兴趣。 strrchr 可用于查找文件名前面的尾随 /

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

int main()
{
char *page = "http://host:port/folder1/folder2/file.jpg";
char *slashes = "//";
char *slash = "/";
char *colon = ":";
char *start = NULL;
char *stop = NULL;
char *host = NULL;
char *port = NULL;
char *path = NULL;
char *file = NULL;
size_t span = 0;

if ( ( start = strstr ( page, slashes)) == NULL) {
fputs ( "could not find \"//\"\n", stderr);
return 1;
}
start += strlen ( slashes);//move pointer so the slashes are excluded
if ( ( stop = strstr ( start, colon)) == NULL) {
fputs ( "could not find \":\"\n", stderr);
return 1;
}
span = stop - start;
if ( ( host = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( host, start, span);
host[span] = '\0';

start = stop + strlen ( colon);
if ( ( stop = strstr ( start, slash)) == NULL) {
fputs ( "could not find leading \"/\"\n", stderr);
return 1;
}
span = stop - start;
if ( ( port = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( port, start, span);
port[span] = '\0';

span = strlen ( stop) + 1;
if ( ( path = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( path, stop, span);
path[span] = '\0';

if ( ( start = strrchr ( page, slash[0])) == NULL) {
fputs ( "could not find trailing \"/\"\n", stderr);
return 1;
}
start += strlen ( slash);
span = strlen ( start) + 1;
if ( ( file = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( file, start, span);
file[span] = '\0';

puts ( host);
puts ( port);
puts ( path);
puts ( file);

free ( host);
free ( port);
free ( path);
free ( file);

return 0;
}

关于c - 迭代 C 中的输入 char 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42747601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com