c语言字符串分割

2023-12-18 17:05:24

代码

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

void extract_fields(char* string) {
    int count = 0;
    char* token;
    char* ptr;
   int ii= 0;
    // Counting the number of occurrences of "-"
    for (int i = 0; string[i] != '\0'; i++) {
        if (string[i] == '-') {
            count++;
        }
    }
    count++;
    printf("%d\n",count);
    // Extracting fields
    ptr = string;
    token = strtok(ptr, "-");
        printf("Field %d before: %s\n", 1, token);


ii=atoi(token);
printf("%d",ii);

    for (int i = 1; i < count; i++) {
        
        token = strtok(NULL, "-");
        printf("Field %d between: %s\n", i, token);
        ptr = NULL;
    }
}

int main() {
    char string[] = "123-12-a-test-string";
    extract_fields(string);
    return 0;
}

在这里插入图片描述

文章来源:https://blog.csdn.net/weixin_38849487/article/details/135064515
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。