本示例介绍C语言中`strtok`函数的基本使用方法,展示如何利用该函数实现字符串的分割操作,并提供代码实例进行说明。
`strtok` 函数是字符串处理库中的一个函数,其原型如下:
```c
char *strtok(char s[], const char *delim);
```
功能:将字符串分解成一系列子串。其中 `s` 是要被分割的原始字符串,而 `delim` 则是一个包含分隔符的字符串。
例如,“hello,hi:what?is!the.matter;” 这个字符串通过传入 `strtok` 函数,并设置第二个参数为 “,:?!.;”,可以得到六个不同的子串。
下面给出一个例子来验证这个功能,比如分割时间的例子:获取UTC时间:
```c
#include
#include
#include
int main() {
time_t now = time(NULL);
struct tm *gmtm = gmtime(&now);
char utc_time[60];
strftime(utc_time, sizeof(utc_time), %Y-%m-%d %H:%M:%S UTC, gmtm);
printf(UTC时间: %s\n, utc_time);
// 使用strtok函数分割获取的UTC时间字符串
const char *delimiters = :- ;
char *token;
token = strtok(utc_time, delimiters);
while (token != NULL) {
printf(%s\n, token); // 输出每个子串
token = strtok(NULL, delimiters);
}
}
```
此代码将展示如何使用 `strtok` 函数来分割时间字符串。