简体   繁体   English

将一个字符串拆分为一个字符串数组,以及一个标志

[英]Split a string to an array of strings, along with a flag

I'm trying to write a code in c that return 1 if there is "&" in the string and 0 otherwise.我正在尝试在 c 中编写代码,如果字符串中有“&”则返回 1,否则返回 0。 In addition, the char* that I receive in the function I want to put it in an array of chars and NULL in the end.另外,我在 function 中收到的char*我想把它放在一个字符数组中,最后放在 NULL 中。 My code is like this:我的代码是这样的:

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; 
}

For example, if the original string (s1) is "Hello I am John &".例如,如果原始字符串 (s1) 是“Hello I am John &”。
So I want s2 to be like:所以我希望 s2 像:

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

And the function will return '1'. function 将返回“1”。 What is wrong with my code?我的代码有什么问题? I debugged it and unfortunately, I don't find the problem.我调试了它,不幸的是,我没有发现问题。

You were shadowing your own parameter.您正在隐藏自己的参数。 See a working example below:请参阅下面的工作示例:

#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++]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM