如何用C编写分割函数(如js)?

问题描述 投票:0回答:1

在 javascript 中,我可以

let sentence = "we have good days";
let words = sentence.split(' ');

for(let i=0;i<words.length;i++) console.log(words[i]);

但我想用 C 语言编写一个 split 函数,就像在 javascript 中一样。

我已经尝试过:

void split(str all,str target[],char s) {
    size_t n = strlen(all);
    int targetN = 0;
    str word;
    int iw = 0;
    for(int i=0;i<n;i++) {
        if(all[i]==' ') { 
            strcpy(target[targetN],word);
            strcpy(word,"");
            iw = 0;
            targetN++;
        } else {
            word[iw] = all[i];
            iw++;
        }
        //word[iw]=
    }

    for(int x=0;x<targetN;x++) { 
        printf("\n %d %s",x,target[x]);
    }
}

这样我可以获取字符串的第一个元素,但不能获取其他元素

如果有人愿意,我可以分享所有代码。我正在尝试编写一个简单的联系人应用程序

我是 C 语言新手

c
1个回答
0
投票
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_WORD_LENGTH 100
#define MAX_WORDS 100

void split(char *all, char target[][MAX_WORD_LENGTH], char s) {
    size_t n = strlen(all);
    int targetN = 0;
    char word[MAX_WORD_LENGTH];
    int iw = 0;

    for (int i = 0; i <= n; i++) {
        if (all[i] == s || all[i] == '\0') { 
            word[iw] = '\0';  // Null-terminate the word
            strcpy(target[targetN], word);
            targetN++;
            iw = 0;
        } else {
            word[iw] = all[i];
            iw++;
        }
    }

    for (int x = 0; x < targetN; x++) { 
        printf("\n %d %s", x, target[x]);
    }
}

int main() {
    char sentence[] = "we have good days";
    char words[MAX_WORDS][MAX_WORD_LENGTH];

    split(sentence, words, ' ');

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.