拆分C​​字符串到使用sscanf的令牌

编程入门 行业动态 更新时间:2024-10-27 17:19:11
本文介绍了拆分C​​字符串到使用sscanf的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想一个字符串分割成令牌,但有些递归。我试图解析:

I'm trying to split a string into tokens but somewhat recursively. I am trying to parse:

"content=0&website=Google"

让我有办法拿出的参数和值。如果我尝试 strtok的我最终摧毁我要解​​析两次字符串。所以,我想

so that I have a way to take out the parameters and values. If I try strtok I end up destroying the string I want to parse twice. So I tried

char *contents = "content=0&website=Google" char arg[100]; char value[100]; sscanf(contents, "%s&%s", arg, value);

作为第一关,希望能解析 ARG 了,但失败了,而 ARG 包含整个字符串。我试着用%S \\&放大器;%的想着&安培; 是一个保留字,但没有运气

as a first pass, hoping to parse arg again, but it fails, and arg contains the entire string. I tried using "%s\&%s" thinking & was a reserved word, but no luck there.

帮助!

编辑:

这是我的strtok黑客:

This was my strtok hack:

static void readParams(char * string, char * param, char * value) { printf("This is the string %s\n",string); char * splitted = strtok (string,"="); while (splitted != NULL) { printf("This is the string %s\n",splitted); splitted = strtok (NULL, "="); // Then do some saving to param and value } } char * splitted = strtok (contents,"&"); int counter = 0; while (splitted != NULL) { char * t_str = strdup(splitted); readParams(t_str, param, value); splitted = strtok (NULL, "&"); }

但它不工作,因为分裂的 strtok的末成为gobbldygook。

but it doesn't work because splitted's strtok at the end becomes gobbldygook.

推荐答案

下面是一个似乎工作的解决方案:

Here is a solution that seems to work:

char *contents = "content=0&website=Google"; char arg[100] = {0}; char value[100] = {0}; sscanf(contents, "%[^&]&%s", arg, value); printf("%s\n%s\n", arg, value);

更多推荐

拆分C​​字符串到使用sscanf的令牌

本文发布于:2023-10-29 22:47:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   字符串   sscanf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!