c - 如果两个数组完全不同则返回 1,如果存在公共(public)元素则返回 0 的函数

标签 c

我已经尝试过这段代码,但它似乎不起作用,如何打破嵌套循环?

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

最佳答案

  1. 您必须初始化 different ,因为如果没有,它是未定义的 - 这可能会破坏您的第一个 while 循环,因为 different 可能是一个随机数 > 1。
  2. strlen 给出字符串中的字符数,不包括终止字符串的空字符(请参阅 here )。但是,您不仅比较两个字符串的字符,还比较空字符,可能是为了隐式检查字符串的长度是否相同。虽然这应该可行,但最好通过首先比较字符串的长度来明确地进行此检查,因为这样更不容易出错。
  3. 如果您首先比较字符串的长度,则无需在此处执行嵌套循环。另外,您现在知道两个字符串的长度,因此可以将该函数更改为使用 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/

相关文章:

C : error: expected expression before ‘.’ token 中的编译错误

用于传递参数的连续内存

c - 重新分配二维数组

c - 总线错误 : 10 in C Program, 无法找出原因

c - 通过滑动窗口协议(protocol)进行数据转换,C

使用递归创建二叉树时调用堆栈错误

java - C 中的 System.nanoTime() 等价物

c - 增加枚举 char[ ] 的指针

c - WIndows系统编程使用标准C库

c - scanf 无法获取 2 个输入 : integer and string from the user