我尝试创建一个挤压函数,删除字符串s1
中与字符串s2
中的任何字符匹配的每个字符。
当我编译时,它并没有说有任何错误,但是由于某种原因没有打印出来。有人能告诉我我在这里做错了什么吗?
void squeeze(char s1[], char s2[]);
int main() {
char s1[] = "abc";
char s2[] = "cde";
squeeze(s1, s2);
printf("%s\t%s", s1, s2); // nothing is being printed...
}
void squeeze(char s1[], char s2[])
{
int i,j,k;
/* i is original s1 index
* j is s2 index
* k is new s1 index
*/
for (i = k = 0; s1[i] != '0'; i++){
for (j = 0; s2[j] != '0'; j++){
if (s1[i] == s2[j])
s1[k++] = s1[i];
}
}
s1[k] = '\0';
}
答案 0 :(得分:1)
上面的代码给出了“分段错误(核心转储)”错误,因为在第二个条件中放置了'0'而不是'\ 0'。即使进行了校正,根据需要,输出对于s1而不是“ab”是“c”。以下代码为s1提供了所需的输出“ab”。
#include <stdio.h>
char * squeeze(char s1[], char s2[]);
int isCharPresent(char c, char s[]);
int main(int argc, char** argv) {
char s1[] = "abc";
char s2[] = "cde";
char * s = squeeze(s1, s2);
printf("%s\t%s\t%s", s, s1, s2);
return 0;
}
char * squeeze(char s1[], char s2[]) {
int i, k;
char *s = malloc(sizeof (s1));
for (i = k = 0; s1[i] != '\0'; i++) {
if (isCharPresent(s1[i], s2) == 0) {
s[k++] = s1[i];
}
}
return s;
}
int isCharPresent(char c, char s[]) {
int i;
for (i = 0; s[i] != '\0'; ++i) {
if (c == s[i]) {
return 1;
}
}
return 0;
}