c语言

C语言函数strtol和strtok怎么用

小亿
93
2023-11-24 03:57:40
栏目: 编程语言

C语言函数strtol和strtok的用法如下:

  1. strtol函数用于将字符串转换为长整型数。其函数原型如下:
long strtol(const char *nptr, char **endptr, int base)

示例代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345abc";
    char *endptr;
    long num = strtol(str, &endptr, 10);
    
    if (endptr == str) {
        printf("No digits were found.\n");
    }
    else {
        printf("The number is: %ld\n", num);
        printf("The next character is: %s\n", endptr);
    }
    
    return 0;
}
  1. strtok函数用于分割字符串。其函数原型如下:
char *strtok(char *str, const char *delim)

示例代码:

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

int main() {
    char str[] = "Hello,World,How,Are,You";
    char *token;
    
    token = strtok(str, ",");
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }
    
    return 0;
}

0
看了该问题的人还看了