【问题标题】:Split a string to an array of strings, along with a flag将一个字符串拆分为一个字符串数组,以及一个标志
【发布时间】:2023-03-10 00:25:01
【问题描述】:

我正在尝试在 c 中编写一个代码,如果字符串中有“&”则返回 1,否则返回 0。 另外,我在函数中收到的char* 我想把它放在一个字符数组中,最后是NULL。 我的代码是这样的:

char** isBackslash(char* s1, int *isFlag) {
    int count = 0;
    isFlag = 0;
    char **s2[100];
    char *word = strtok(s1, " ");
    while (word != NULL) {
        s2[count] = word;
        if (!strcmp(s2[count], "&")) {
            isFlag = 1;
        }
        count++;
        word = strtok(NULL, " ");
    }
    s2[count] = NULL;
    return s2; 
}

例如,如果原始字符串 (s1) 是“Hello I am John &”。
所以我希望 s2 是这样的:

s2[0] = Hello
s2[1] = I
s2[2] = am
s2[3] = John
s2[4] = &
s2[5] = NULL

该函数将返回“1”。我的代码有什么问题?我调试了它,不幸的是,我没有发现问题。

【问题讨论】:

  • char *s2[50]; 你正在隐藏参数s2
  • char *s2[50] 是一个局部变量;当函数返回时它消失了。你还有一个参数char *s2——它被局部变量隐藏了。你有一些严肃的想法要做。您可能需要将参数变为char *s2[]char **s2,然后删除本地版本。
  • 改成char ** isBackslash(char* s1, int *isFlag)可能更容易
  • 如果你想使用动态分配,你需要回到使用malloc/realloc的第二个版本。只需将s2 更改为局部变量并在最后返回即可。
  • 您好佩德罗,请参阅我的答案以获得一个工作示例,请不要编辑太多或保留旧版本,否则我的答案将没有意义

标签: c string strcmp strcpy


【解决方案1】:

你在隐藏你自己的参数。请参阅下面的工作示例:

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

#define BUFF_SIZE 256

int isBackslash(char* s1, char s2[][BUFF_SIZE]) {
    int isFlag = 0;
    int i = 0;
    int j = 0;
    int n = 0;

    while (s1[i] != '\0') {
        isFlag |= !('&' ^ s1[i]); // will set the flag if '&' is met
        if (s1[i] == ' ') {
            while (s1[i] == ' ')
                i++;
            s2[n++][j] = '\0';
            j = 0;
        }
        else 
            s2[n][j++] = s1[i++];
    }

    return isFlag;
}

int main(void) {
    char s2[BUFF_SIZE/2+1][BUFF_SIZE];
    memset(s2, 0, sizeof(s2));

    char s1[BUFF_SIZE] =  "Hello I am John &";
    int c = isBackslash(s1, s2);


    printf("%d\n", c);

    int i = 0;
    while (s2[i][0] != '\0')
        printf("%s\n", s2[i++]);
}

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多