溫馨提示×

C語言string方法怎樣處理字符串分割

小樊
82
2024-09-29 15:15:07
欄目: 編程語言

在 C 語言中,沒有內(nèi)置的 string 分割函數(shù),但我們可以使用一些簡單的方法來實現(xiàn)字符串分割。以下是一個使用 C 語言實現(xiàn)的字符串分割函數(shù)示例:

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

// 分割字符串的回調(diào)函數(shù)
char* split(const char *str, const char *delim, int *count) {
    char *token = strtok(str, delim);
    char *result = NULL;
    *count = 0;

    while (token != NULL) {
        result = realloc(result, (*count + 1) * sizeof(char));
        strcpy(result + *count * sizeof(char), token);
        (*count)++;
        token = strtok(NULL, delim);
    }

    return result;
}

int main() {
    const char *input = "Hello,World,This,Is,A,Test";
    const char *delimiter = ",";
    int count;
    char **split_result = split(input, delimiter, &count);

    printf("Split result:\n");
    for (int i = 0; i < count; i++) {
        printf("%s\n", split_result[i]);
    }

    // 釋放分配的內(nèi)存
    for (int i = 0; i < count; i++) {
        free(split_result[i]);
    }
    free(split_result);

    return 0;
}

在這個示例中,我們定義了一個名為 split 的函數(shù),它接受一個字符串 str、一個分隔符 delim 以及一個用于存儲分割后的字符串數(shù)量的指針 count。函數(shù)的返回值是一個指向分割后的字符串數(shù)組的指針。

我們使用 strtok 函數(shù)來分割字符串。strtok 函數(shù)會根據(jù)分隔符 delim 來分割字符串 str,并返回一個指向分割后的子字符串的指針。我們在 split 函數(shù)中使用一個循環(huán)來處理所有的分割結(jié)果,并將它們存儲在一個動態(tài)分配的字符串數(shù)組中。

main 函數(shù)中,我們調(diào)用 split 函數(shù)來分割一個示例字符串,并打印分割后的結(jié)果。最后,我們釋放分配的內(nèi)存。

0