如何解决将字符串拆分为字符串数组以及标志
我正在尝试用 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”。我的代码有什么问题?我调试了它,不幸的是,我没有发现问题。
解决方法
您正在隐藏自己的参数。请参阅下面的工作示例:
#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,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++]);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。