我已经尝试过这段代码,但它似乎不起作用,如何打破嵌套循环?
#include <stdio.h>
#include <string.h>
int meme(char s1[], char s2[])
{
int i = 0, j = 0;
int different;
while (i <= strlen(s1) && different == 1) {
while (j <= strlen(s2)) {
if (s1[i] != s2[j]) {
different = 1;
} else {
different = 0;
}
j = j + 1;
}
i = i + 1;
}
return different;
}
最佳答案
- 您必须初始化
different
,因为如果没有,它是未定义的 - 这可能会破坏您的第一个 while 循环,因为different
可能是一个随机数 > 1。 strlen
给出字符串中的字符数,不包括终止字符串的空字符(请参阅 here )。但是,您不仅比较两个字符串的字符,还比较空字符,可能是为了隐式检查字符串的长度是否相同。虽然这应该可行,但最好通过首先比较字符串的长度来明确地进行此检查,因为这样更不容易出错。- 如果您首先比较字符串的长度,则无需在此处执行嵌套循环。另外,您现在知道两个字符串的长度,因此可以将该函数更改为使用 for 循环,这使其更加简单。
基于上述几点的可能解决方案:
#include <stdio.h>
#include <string.h>
int meme(char s1[], char s2[]){
int i = 0;
int len_s1 = 0;
int len_s2 = 0;
int different = 0;
len_s1 = strlen(s1);
len_s2 = strlen(s2);
if (len_s1 == len_s2) {
for (i = 0 ; i < len_s1 ; i++) {
if (s1[i] != s2[i]) {
different = 1;
break;
}
}
else {
different = 1;
}
return different;
}
还有一件事 - 帮自己和其他人一个忙,并计划好你的代码,否则很难阅读!
关于c - 如果两个数组完全不同则返回 1,如果存在公共(public)元素则返回 0 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456375/