c语言中strtok函数_在C语言中使用strtok()和strtok_r()函数

2023-05-16

c语言中strtok函数

In this article, we’ll take a look at using the strtok() and strtok_r() functions in C.

在本文中,我们将介绍如何在C语言中使用strtok()和strtok_r()函数。

These functions are very useful, if you want to tokenize a string. C provides these handy utility functions to split our input string into tokens.

如果要标记字符串,这些功能非常有用。 C提供了这些方便的实用程序函数,可将我们的输入字符串拆分为标记。

Let’s take a look at using these functions, using suitable examples.

让我们使用合适的示例来看看如何使用这些功能。



使用strtok()函数 (Using the strtok() function)

First, let’s look at the strtok() function.

首先,让我们看一下strtok()函数。

This function is a part of the <string.h> header file, so you must include it in your program.

此函数是<string.h>头文件的一部分,因此必须在程序中包含它。


#include <string.h>

char* strtok(char* str, const char* delim);

This takes in an input string str and a delimiter character delim.

这将接受输入字符串str和定界符delim

strtok() will split the string into tokens based on the delimited character.

strtok()将根据定界字符将字符串拆分为标记。

We expect a list of strings from strtok(). But the function returns us a single string! Why is this?

我们期望从strtok()获得字符串列表。 但是该函数返回一个字符串! 为什么是这样?

The reason is how the function handles the tokenization. After calling strtok(input, delim), it returns the first token.

原因是该函数如何处理标记化。 调用strtok(input, delim) ,它返回第一个标记。

But we must keep calling the function again and again on a NULL input string, until we get NULL!

但是我们必须继续在NULL输入字符串上一次又一次地调用该函数,直到获得NULL为止!

Basically, we need to keep calling strtok(NULL, delim) until it returns NULL.

基本上,我们需要继续调用strtok(NULL, delim)直到返回NULL

Seems confusing? Let’s look at an example to clear it out!

似乎令人困惑? 让我们看一个例子来清除它!


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

int main() {
    // Our input string
    char input_string[] = "Hello from JournalDev!";

    // Our output token list
    char token_list[20][20]; 

    // We call strtok(input, delim) to get our first token
    // Notice the double quotes on delim! It is still a char* single character string!
    char* token = strtok(input_string, " ");

    int num_tokens = 0; // Index to token list. We will append to the list

    while (token != NULL) {
        // Keep getting tokens until we receive NULL from strtok()
        strcpy(token_list[num_tokens], token); // Copy to token list
        num_tokens++;
        token = strtok(NULL, " "); // Get the next token. Notice that input=NULL now!
    }

    // Print the list of tokens
    printf("Token List:\n");
    for (int i=0; i < num_tokens; i++) {
        printf("%s\n", token_list[i]);
    }

    return 0;
}

So, we have our input string “Hello from JournalDev!”, and we’re trying to tokenize it by spaces.

因此,我们有输入字符串“ Hello from JournalDev!”,我们正在尝试用空格标记它。

We get the first token using strtok(input, " "). Notice the double quotes, as the delimiter is a single character string!

我们使用strtok(input, " ")获得第一个令牌。 注意双引号,因为定界符是单个字符串!

Afterwards, we keep getting tokens using strtok(NULL, " ") and loop until we get NULL from strtok().

之后,我们继续使用strtok(NULL, " ")获取令牌并循环,直到从strtok()获取NULL

Let’s look at the output now.

现在让我们看一下输出。

Output

输出量


Token List:
Hello
from
JournalDev!

Indeed, we seem to have got the correct tokens!

确实,我们似乎已经获得了正确的令牌!

Similarly, let’s now look at using strtok_r().

同样,让我们​​现在来看一下使用strtok_r()



使用strtok_r()函数 (Using the strtok_r() function)

This function is very similar to the strtok() function. The key difference is that the _r means that this is a re-entrant function.

此函数与strtok()函数非常相似。 关键区别在于_r表示这是可重入函数。

A reentrant function is a function that can be interrupted during its execution. This type of function can also be safely called again, to resume execution!

可重入函数是可以在其执行期间中断的函数。 也可以再次安全地调用此类函数,以恢复执行!

This is why it is a “re-entrant” function. Just because it can safely enter again!

这就是为什么它是“可重入”功能的原因。 只是因为它可以安全地再次进入!

Due to this fact, re-entrant functions are thread-safe, meaning that they can safely be interrupted by threads, just because they can resume again without any harm.

因此,重入函数是线程安全的,这意味着它们可以安全地被线程中断,因为它们可以再次恢复而不会造成任何伤害。

Now, similar to strtok(), the strtok_r() function is a thread-safe version of it.

现在,类似于strtok()strtok_r()函数是该线程的线程安全版本。

However, this has an extra parameter to it, called the context. We need this, so that the function can resume from the right place.

但是,这有一个额外的参数,称为context 。 我们需要这样做,以便函数可以从正确的位置恢复。

NOTE: If you’re using Windows, the equivalent function is strtok_s(). strtok_r() is for Linux / Mac based systems!

注意 :如果使用的是Windows,则等效功能为strtok_s()strtok_r()适用于基于Linux / Mac的系统!


#include <string.h>

char *strtok_r(char *str, const char *delim, char **context);

The context parameter is a pointer to the character, which strtok_r uses internally to save its state.

context参数是指向字符的指针, strtok_r内部使用该指针保存其状态。

Usually, we can just pass it from a user-declared pointer.

通常,我们可以从用户声明的指针传递它。

Let’s look at the same example for strtok(), now using strtok_r() (or strtok_s() on Windows).

让我们看一下strtok()的相同示例,现在使用strtok_r() (或Windows上的strtok_s() )。


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

int main() {
    // Our input string
    char input_string[] = "Hello from JournalDev!";

    // Our output token list
    char token_list[20][20]; 

    // A pointer, which we will be used as the context variable
    // Initially, we will set it to NULL
    char* context = NULL;

    // To get the value of the context variable, we can pass it's address
    // strtok_r() to automatically populate this context variable, and refer
    // it's context in the future
    char* token = strtok_r(input_string, " ", &context);

    int num_tokens = 0; // Index to token list. We will append to the list

    while (token != NULL) {
        // Keep getting tokens until we receive NULL from strtok()
        strcpy(token_list[num_tokens], token); // Copy to token list
        num_tokens++;
        token = strtok_r(NULL, " ", &context); // We pass the context variable to strtok_r
    }

    // Print the list of tokens
    printf("Token List:\n");
    for (int i=0; i < num_tokens; i++) {
        printf("%s\n", token_list[i]);
    }

    return 0;
}

Output

输出量


Token List:
Hello
from
JournalDev!

While we get the same output, this version is better, since it is thread safe!

虽然我们得到相同的输出,但是此版本更好,因为它是线程安全的!



结论 (Conclusion)

In this article, we learned about how we could use the strtok() and strtok_r() functions in C, to tokenize strings easily.

在本文中,我们学习了如何在C中使用strtok()和strtok_r()函数轻松地对字符串进行标记。

For similar content, do go through our tutorial section on C programming!

对于类似的内容,请阅读我们有关C编程的教程部分!

参考资料 (References)

  • Linux manual page on strtok() and strtok_r() functions in C

    有关C语言中strtok()和strtok_r()函数的Linux手册页


翻译自: https://www.journaldev.com/42293/strtok-strtok-r-functions-c

c语言中strtok函数

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c语言中strtok函数_在C语言中使用strtok()和strtok_r()函数 的相关文章

  • strtok函数

    头文件 string h 函数声明 char strtok xff08 char str xff0c const sep xff09 返回值 分隔符之前字符串的首地址 用法 sep的参数是个字符串 xff0c 定义了用作分隔符的字符集合st
  • C++ strtok的用法

    size 61 large align 61 center strtok的用法 align size 函数原型 xff1a char strtok char s char delim 函数功能 xff1a 把字符串s按照字符串delim进行
  • c语言中strtok函数_在C语言中使用strtok()和strtok_r()函数

    c语言中strtok函数 In this article we ll take a look at using the strtok and strtok r functions in C 在本文中 xff0c 我们将介绍如何在C语言中使用
  • C语言:strtok()的用法。

    char strtok char str const char sep 1 sep参数是个字符串 xff0c 定义了用作分隔符的字符集合 xff1b 2 第一个参数指定一个字符串 xff0c 它包含了0个或者多个由sep字符串中一个或者多个
  • C++ strtok()无法截取连续两个分隔符之间的空字符串, 解决方法

    前言 问题描述 与前台约定按顺序解析对应信息 如果中间出现空数据 或者出现连续两个分隔符 strtok就会出问题 看下面这个例子 1 include lt string h gt 2 include lt stdio h gt 3 4 in
  • C语言strtok函数

    1 strtok 语法 include lt string h gt char strtok char str const char delimiters 参数 xff1a str xff0c 待分割的字符串 xff08 c string
  • c strtok()

    分解字符串为一组字符串 s为要分解的字符 xff0c delim为分隔符字符 xff08 如果传入字符串 xff0c 则传入的字符串中每个字符均为分割符 xff09 首次调用时 xff0c s指向要分解的字符串 xff0c 之后再次调用要把
  • matlab学习(1)strsplit与strtok

    strsplit函数用法 xff1a lt 1 gt 默认使用空格符分割 返回一个cell数组 lt 2 gt 也可以指定第二个参数进行分割 lt 3 gt 第二个参数也可以时包含多个分隔符的元胞数组 lt 4 gt strsplit还可以
  • 字符串分割函数--strtok与strsep

    在 c 中 字符串分割函数主要有两种 一是strtok函数 另一个就是strsep函数 下面我们对这两个函数作一个详细解释说明 1 strtok 原形 char strtok char str const char delim 功能 分解字
  • 分解命令行字符串为argc和argv

    有时候需要用空格把一个命令行参数字符串分解为参数个数和参数指针 就是常见的c语言main 函数入口argc argv 这里采用strtok 函数可以很方便的做到 char strtok char str const char delim 用
  • 使用 fgets 和 strtok 从文件中读取和解析行

    我在编写相当基本的代码时遇到了麻烦 我需要从下面所示的文件中读取每一行 用 strtok 将其分成 3 部分 并将每个部分存储到一个数组中 目标 和 助攻 的数组工作正常 但由于某种原因 整个名称数组都填充了从文件中读取的姓氏 输入文件 R
  • 具有连续分隔符的 strtok_s 行为

    我正在并行解析 3 个值 这些值用特定的分隔符分隔 token1 strtok s str1 separator nextToken1 token2 strtok s str2 separator nextToken2 token3 str
  • 实现分隔符具有多个字符的“strtok”

    代码片段 char str String1 String2 String3 String4 String5 char deli char token strtok str deli while token NULL printf Token
  • 根据空格或“双引号字符串”将字符串解析为数组

    我试图获取用户输入字符串并解析为一个名为 char entire line 100 的数组 其中每个单词都放在数组的不同索引处 但如果字符串的一部分用引号封装 则应将其放在单个索引中 所以如果我有 char buffer 1024 0 fg
  • 罢工行为

    int main char str kk 12 23 4 3434 3 33 char valarr int count 0 valarr strtok str while valarr 0 valarr strtok NULL count
  • Arduino 错误:无法将参数 '1' 的 'String' 转换为 'char*' 到 'char* strtok(c​​har*, const char*)'

    我正在研究一个 arduino 分配 它分割传入的字符串并将字符串的术语放入 6 个不同的变量中 分割时的示例输入字符串有 6 个术语 我弹出以下错误 无法将参数 1 的 String 转换为 char 到 char strtok c ha
  • 开发了 strtok 替代品

    我开发了自己的 strtok 版本 只是为了练习指针的使用 任何人都可以看到这有任何限制 或者无论如何我可以改进 void stvstrtok const char source char dest const char token Sea
  • 在C中提取两个特定字符串之间的字符串

    如何提取两个指定字符串之间的字符串 例如 有没有一种简单的方法可以使用它strtok 或者更简单的东西 编辑 两个指定的字符串是提取的字符串是Extract this 使用搜索第一个子字符串strstr 如果找到 则保存子字符串的数组索引
  • 同时标记多个字符串

    假设我有三个 C 风格的字符串 char buf 1 1024 char buf 2 1024 and char buf 3 1024 我想对它们进行标记 并使用所有三个标记中的第一个标记执行操作 然后对所有三个标记中的第二个标记执行相同的
  • 使用 strtok 在 C 中解析字符串

    我有这个小源代码 用于测试类似于变量的字符串的解析string我需要在其他项目中使用 include

随机推荐

  • 初探Nacos(一)-- 单机模式启动

    花小钱 xff0c 周边游 xff0c 马上抢 xff0c 请关注公众号 xff1a 爱订不订 作者 xff1a 唐璜 前言 Nacos 支持基于 DNS 和基于 RPC 的服务发现 xff08 可以作为springcloud的注册中心 x
  • 筹码集中度90与70区别是什么?

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 筹码集中度是指一只个股的筹码被庄家掌握的程度 我们看到不同的数值 xff0c 比如说90和70 xff0c 很多的股民都不知道筹码集中度90与70区别是什么 下边小编会为大
  • Caused by: org.xml.sax.SAXParseException: 文件提前结束。

    Error starting ApplicationContext To display the auto configuration report re run your application with 39 debug 39 enab
  • AHB总线协议(一)

    1 简介 AHB Advanced High Performance Bus 总线规范是AMBA Advanced Microcontroller Bus Architecture V2 0总线规范的一部分 xff0c AMBA总线规范是A
  • iOS 4.5.5版本 被拒绝!!!! "App Rejected : non-public APIs"

    今天上午收到邮件说是被拒绝了 原文是 这一版本 我就添加一个购买sku的方法 并没有添加什么库 简简单单的一次升级给我出一私有方法拒绝 在xcode8 iOS10 刚出来 苹果新规则进一步丰富 出现这种意外的问题 一定不只我一个 的确 我在
  • 删除文件夹及其子文件

    rm rf 目录 转载于 https www cnblogs com tiandsp archive 2012 07 09 2583207 html
  • 树莓派练习程序(土壤湿度检测)

    土壤湿度检测模块如下 xff1a 树莓派的引脚如下图 xff1a 我们将Vcc引脚连接物理接口2 xff0c GND引脚连接物理接口39 xff0c DO引脚连接物理接口40 实物连接如下图 xff1a 编程使用WiringPi库 xff0
  • 搞定面试问题-进程、线程、协程

    关于进程 xff0c 线程 xff0c 协程是面试中经常可见的问题 xff0c 接下来这篇文章帮你梳理一下 xff0c 让你轻松应对面试官 1 xff0c 什么是进程 一个程序的执行实例就是一个进程 每一个进程提供执行程序所需的所有资源 x
  • OVN 架构分析

    架构分析Base flow L2 L3 forwardingOVN L2 gateway OVN 是 Open vSwitch 社区在 2015 年 1 月份才宣布的一个子项目 xff0c OVN 使用 Open vSwitch功能提供一个
  • fyi 在邮件里是什么意思_FYI的完整形式是什么?

    fyi 在邮件里是什么意思 仅供参考 xff1a 供您参考 FYI For Your Information FYI is an acronym of 34 For Your Information 34 It is a widesprea
  • Maven war包相互依赖

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 假设有两个war包 xff1a A和B A又依赖于B 根据Java规范 xff0c classpath不能指定WAR文件 这就意味着在编译时 xff0c A项目无法访问B项
  • 没事儿乱冒点皮皮

    快一个月没写Blog了 xff0c 这段时间忙着应付考试 xff0c 也就没花太多的时间管这些 前天刚刚考完四级 xff0c 感觉还不错 xff0c 希望能过吧 xff0c 虽然这次我还是没怎么努力学英语 xff0c 如果说真的过了 xff
  • AutoLISP对话框DCL按钮Button设计实例

    AutoLISP对话框DCL按钮设计实例 xff0c 绘制三种形式的图形 xff0c DCL对话框设计代码如下 dia5b dialog label 61 34 按钮测试 34 boxed row label 61 34 图形尺寸 34 e
  • 教你如何修改运行中的docker容器的端口映射

    在docker run创建并运行容器的时候 xff0c 可以通过 p指定端口映射规则 但是 xff0c 我们经常会遇到刚开始忘记设置端口映射或者设置错了需要修改 当docker start运行容器后并没有提供一个 p选项或设置 xff0c
  • svn status 显示 ~xx

    版本控制下的项目与其它类型的项目重名
  • python键盘输入转换为列表_Python键盘输入转换为列表的实例

    Python键盘输入转换为列表的实例 发布时间 xff1a 2020 08 19 12 58 38 来源 xff1a 脚本之家 阅读 xff1a 92 作者 xff1a 清泉影月 Python输入字符串转列表是为了方便后续处理 xff0c
  • 如何调试带有源代码的dll文件

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 工作环境 xff1a dll源代码是c xff0c 在Visual studio 2010中调试 第一步 xff0c 调试的准备 用C 语言编写一个测试dll文件的程序 x
  • (网上搜集)金蝶报错:名称或代码在系统中已被使用

    KIS专业版 修正核算项目关系 select from t itemdetail exec sp cleanitemdetailv GO update a set a fdetailcount 61 b Fcount from t item
  • Xmanager 远程连接linux ubuntu桌面操作系统

    Xmanager 远程连接linux ubuntu桌面操作系统 Xmanager 下载地址 url http dl pconline com cn download 53773 html url 1 ubuntu desk操作系统的配置 系
  • c语言中strtok函数_在C语言中使用strtok()和strtok_r()函数

    c语言中strtok函数 In this article we ll take a look at using the strtok and strtok r functions in C 在本文中 xff0c 我们将介绍如何在C语言中使用