C语言字符串分割:将'123+123'分割并赋值给变量

您是否需要将字符串 '123+123' 按照 '+' 进行分割,并将分割后的子字符串赋值给 abcmdef 等变量?以下是一段C代码示例,演示如何实现此功能:

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

void splitString(const char* input, char* output[], int* count) {
    char* token;
    *count = 0;

    // 使用strtok函数切分字符串
    token = strtok((char*) input, '+');
    while (token != NULL) {
        output[*count] = malloc(strlen(token) + 1);
        strcpy(output[*count], token);
        (*count)++;
        token = strtok(NULL, '+');
    }
}

int main() {
    const char* input = '123+123';
    char* abcmdef[10]; // 假设最多10个子字符串
    int count;

    splitString(input, abcmdef, &count);

    // 打印赋值后的结果
    for (int i = 0; i < count; i++) {
        printf('%s\n', abcmdef[i]);
        free(abcmdef[i]);
    }

    return 0;
}

代码解释:

  1. splitString 函数:

    • 接受输入字符串 input,输出字符串数组 output,以及存储子字符串数量的 count
    • 使用 strtok 函数将输入字符串按照 '+' 分割成多个子字符串。
    • 为每个子字符串动态分配内存,并将其复制到 output 数组中。
    • 更新 count 以跟踪子字符串的数量。
  2. main 函数:

    • 定义输入字符串 input 和存储子字符串的数组 abcmdef
    • 调用 splitString 函数进行字符串分割。
    • 遍历 abcmdef 数组,打印每个子字符串。
    • 释放为子字符串动态分配的内存。

注意:

  • abcmdef 数组的大小需要根据实际情况进行调整,以确保能够存储所有分割后的子字符串。
  • 使用完动态分配的内存后,需要及时释放,以避免内存泄漏。

希望这个示例能够帮助您理解如何在 C 语言中分割字符串并将子字符串赋值给指定变量!

C语言字符串分割:将'123+123'分割并赋值给变量

原文地址: https://www.cveoy.top/t/topic/brvQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录