c - 如何在没有 sscanf 的情况下解析 URL 字符串
问题描述
我在解析 URL 时遇到问题(例如http://user:pass@example.com:6379/8?client_name=itisme&timeout=0.5&timeout_connect=0.25),我需要这个输出或类似的输出:
TCP = http
user = user
password = pass
host = example.com
port = 6379
number = 8
array of parametrs = {"client_name","itisme", "timeout","0.5","timeout_connect","0.25"}
有没有比使用 strtok() 和巨大的 switch/case 更好的方法?
这里:是我的解析函数,我可以使用用户获取输入参数 Url 并传递或忽略它。
Conn_Properties ConnProp(char *URL)
{
Conn_Properties result;
bool Password = false;
int i;
for (i=0;i<strlen(URL);++i)
{
if (URL[i]=='@')
{
Password = true;
break;
}
}
char * pch;
pch = strtok (URL,"@:/?");
int cnt_loop = 1;
while (pch != NULL)
{
switch (cnt_loop)
{
case 1:
result.TCPconn = pch;
break;
case 2:
if (Password)
if (strcmp(result.TCPconn,"redis")==0)
result.user = pch;
if (strcmp(result.TCPconn,"redis+sentinel")==0 && Password)
result.Sentinel_pass = pch;
break;
case 3:
if (strcmp(result.TCPconn,"redis+sentinel")==0 && Password)
result.Sentinel_pass = pch;
if (strcmp(result.TCPconn,"redis")==0 && Password)
result.Redis_pass = pch;
break;
case 4:
result.DNS_name = pch;
break;
case 5:
result.DNS_port = pch;
break;
case 6:
result.DB_number = pch;
break;
default:
break;
}
switchstr(pch) {
casestr("client_type")
result.client_type = strtok (NULL,"=&");
break;
casestr("client_name")
result.client_name = strtok (NULL,"=&");
break;
casestr("password")
result.Redis_pass = strtok (NULL,"=&");
break;
casestr("timeout")
pch = strtok (NULL,"=&.");
result.timeout = TValcreator(pch);
result.timeout_present = true;
break;
casestr("timeout_connect")
pch = strtok (NULL,"=&.");
result.timeout_conn= TValcreator(pch);
result.timeout_conn_present = true;
break;
casestr("db")
result.DB_number = strtok (NULL,"=&");
break;
casestr("service_name")
result.service_name = strtok (NULL,"=&");
break;
casestr("accessmode")
result.accessmode = strtok (NULL,"=&");
break;
casestr("accesstestkey")
result.accesstestkey = strtok (NULL,"=&");
break;
casestr("stimeout")
pch = strtok (NULL,"=&");
result.stimeout = TValcreator(pch);
result.stimeout_present = true;
break;
casestr("stimeout_result")
pch = strtok (NULL,"=&.");
result.stimeout_result= TValcreator(pch);
result.stimeout_result_present = true;
break;
defaultstr
break;
} switchstr_end;
pch = strtok (NULL, "@:/?%=&");
if (Password && (cnt_loop==1 || cnt_loop==2))
++cnt_loop;
else
if (!Password && cnt_loop==1)
cnt_loop = 4;
else
if (!Password && cnt_loop>=3)
++cnt_loop;
else
++cnt_loop;
}
return result;
}
解决方案
推荐阅读
- java - 如何将外部 jar 添加到 Webots?
- c# - 如何将单个类型的正确实例注入另一个类
- javascript - 如何在函数内部传递一个作为访问属性的参数
- c# - 如何使用重定向在 asp.net core 2.0 的新选项卡中打开链接
- python-3.x - O(1) 设置位计数
- vue.js - Vue: filter an array of objects doesn't work properly
- eclipse - Prevent Eclipse from collapsing a path in project explorer that I manually opened?
- javascript - How can I combine multiple scroll event listeners into one?
- javascript - 正则表达式测试不适用于数字
- docker - 在运行 HornetQ 的两个 Docker 容器之间共享数据文件