我在网上看到了一个答案,我不明白它是如何与那个循环一起工作的。为什么我的work.The问题是:编写一个squeeze(s1,s2)的替代版本,删除字符串s1中与字符串s2中任何字符匹配的每个字符。我认为它应该检查s1中不匹配s2中每个字符的每个字符。就像您在s1中看到一个字符一样,您可以循环遍历s2,查看它是否与s1中的字符匹配,然后转到s1中的下一个字符。因此,外部循环用于s1,内环用于s2。这是他的代码,我把它放在一个完整的代码中来测试它。他的输出是正确的。他的代码是功能部分。我不明白的是,为什么他把s2放在外部循环中,它甚至可以工作。
#include <string.h>
#include <stdio.h>
void squeeze2(char s[], char t[]);
void squeeze2(char s[], char t[]) {
int i, j, k;
for (k = 0; t[k] != '\0'; k++) {
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != t[k])
s[j++] = s[i];
s[j] = '\0';
}
}
int main() {
char s1[] = "hello meow meow princess";
char s2[] = { 'a', 'e', 'm' };
squeeze2(s1, s2);
int i = 0;
while (s1[i] != '\0') {
printf("%c", s1[i]);
i++;
}
}还有我的。我在内部代码中加入了S2,它的输出是喵喵公主。
#include <string.h>
#include <stdio.h>
void squeeze(char s1[],char s2[]);
int main() {
char s1[] = "hello meow meow princess";
char s2[] = { 'a', 'e', 'm' };
squeeze(s1, s2);
int l;
for (l = 0; l < strlen(s1); l++)
printf("%c", s1[l]);
}
void squeeze(char s1[], char s2[]) {
int i = 0;
int k = 0;
while (s1[i] != '\0')
for (int j = 0; s2[j] != '\0'; j++) {
if (s1[i] != s2[j]) {
s1[k] = s1[i];
k++;
}
i++;
}
}发布于 2016-11-05 21:34:40
实际上,不管您是先在s1上循环,下一个在s2上循环,还是反过来循环,只要您修改了实际的代码。
这两个版本都存在一个问题:main中的字符串main不为null (它不是C字符串),因此squeeze中的行为未被定义为第二个字符串中的字符将在数组结束后被取消引用。
在您的版本中还有更多问题:
s1中找到了它的一个或多个字符,则不为null终止它。s1的每个字符的次数与从s2中找到不匹配字符的次数一样多。相反,您应该通过调用s2或手工枚举来验证字符是否存在于strchr(s2, s1[i])中。
以下是一个经过修正和简化的版本:
#include <string.h>
#include <stdio.h>
void squeeze(char *s1, const char *s2);
int main(void) {
char s1[] = "hello meow meow princess";
char s2[] = { 'a', 'e', 'm', '\0' };
squeeze(s1, s2);
printf("%s\n", s1);
return 0;
}
void squeeze(char *s1, const char *s2) {
int i, j, k;
for (i = k = 0; s1[i] != '\0'; i++) {
for (j = 0; s2[j] != '\0'; j++) {
if (s1[i] == s2[j])
break;
}
if (s2[j] == '\0') { // character was not found in s2
s1[k++] = s1[i];
}
}
s1[k] = '\0'; // null terminate s1 of it was shortened
}备注:
if、else、for、while和do ... while之后为非平凡语句使用大括号。for而不是while:分组索引变量的初始化、增量和测试可以提高可读性,减少bug。l:使用恒定宽度的字体,它看起来与1太相似了。const限定未被函数修改的字符串参数。https://stackoverflow.com/questions/40442736
复制相似问题