如何从 C 中的字符串中解析标记?

发布于 2024-07-13 09:18:15 字数 150 浏览 5 评论 0原文

如何从输入字符串中解析标记。 例如:

char *aString = "Hello world".

我希望输出为:

“你好”“世界”

How do i parse tokens from an input string.
For example:

char *aString = "Hello world".

I want the output to be:

"Hello" "world"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半山落雨半山空 2024-07-20 09:18:15

您将要使用 strtok - 这里是一个很好的例子。

You are going to want to use strtok - here is a good example.

浮生面具三千个 2024-07-20 09:18:15

看一下 strtok,它是标准库的一部分。

Take a look at strtok, part of the standard library.

以为你会在 2024-07-20 09:18:15

strtok 是一个简单的答案,但您真正需要的是一个能够正确执行此操作的词法分析器。 考虑以下问题:

  • “hello”和“world”之间是否有一两个空格?
  • 实际上可以有任意数量的空白吗?
  • 可以包含垂直空白(\n、\f、\v)还是仅包含水平空白(\s、\t、\r)?
  • 可以包含任何 UNICODE 空白字符吗?
  • 如果单词之间有标点符号(“你好,世界”),该标点符号是一个单独的标记,是“你好”的一部分,还是被忽略?

正如您所看到的,编写一个正确的词法分析器并不简单,而且 strtok 也不是一个正确的词法分析器。

其他解决方案可能是一个单字符状态机,它可以精确地满足您的需要,或者是基于正则表达式的解决方案,使定位单词与间隙更加通用。 有很多方法。

当然,这一切都取决于你的实际需求是什么,我也不知道,所以从strtok开始。 但了解各种限制是有好处的。

strtok is the easy answer, but what you really need is a lexer that does it properly. Consider the following:

  • are there one or two spaces between "hello" and "world"?
  • could that in fact be any amount of whitespace?
  • could that include vertical whitespace (\n, \f, \v) or just horizontal (\s, \t, \r)?
  • could that include any UNICODE whitespace characters?
  • if there were punctuation between the words, ("hello, world"), would the punctuation be a separate token, part of "hello,", or ignored?

As you can see, writing a proper lexer is not straightforward, and strtok is not a proper lexer.

Other solutions could be a single character state machine that does precisely what you need, or regex-based solution that makes locating words versus gaps more generalized. There are many ways.

And of course, all of this depends on what your actual requirements are, and I don't know them, so start with strtok. But it's good to be aware of the various limitations.

拥抱影子 2024-07-20 09:18:15

对于可重入版本,您可以使用
用于 Visual Studio 的 strtok_sstrtok_r for unix

For re-entrant versions you can either use
strtok_s for visual studio or strtok_r for unix

面犯桃花 2024-07-20 09:18:15

请记住,strtok非常很难得到正确的结果,因为:

  • 它修改输入
  • 分隔符被空终止符替换
  • 合并相邻的分隔符,当然,
  • 不是线程安全的。

您可以阅读有关此替代方案的信息。

Keep in mind that strtok is very hard to get it right, because:

  • It modifies the input
  • The delimiter is replaced by a null terminator
  • Merges adjacent delimiters, and of course,
  • Is not thread safe.

You can read about this alternative.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文