gpt4 book ai didi

c - 在 c 中比较不相等的 char 数组的正确方法

转载 作者:行者123 更新时间:2023-12-04 11:38:52 25 4
gpt4 key购买 nike

如果两个字符数组的长度不相等,是否有比较正确的方法?如何检查哪个字符不相等?

strcmp 似乎只给我更大或更小的数字,而不是不等字符的位置。

例如,字符串:

/home/jjjj/ and
/home/jjjj/kkkk/asdasd

应该返回 12

最佳答案

使用 strlen()strstr() 您可以分两步实现:

#include <string.h>
#include <stdio.h>
...


char str1[] = "this is a long string";
char str2[] = "long";

{
char * ss = NULL;
char * sg = NULL;
size_t size1 = strlen(str1)
size_t size2 = strlen(str2);
size_t size_ss = 0;

/* step 1: determine which of the two strings tobe compared it the smaller/greater one. */
if (size1 > size2)
{
size_ss = size2;
ss = str2;
sg = str1;
}
else
{
size_ss = size1;
ss = str1;
sg = str2;
}

/* step 2: find out where the smaller string is located in the greater one, if ever... */
{
char * p = strstr(sg, ss);

if (p)
{
printf("'%s' is the same as '%s' from character %zu to character %zu.\n",
sg, ss, p - sg, p - sg + size_ss);
}
else
{
/* printf("The strings are 100%% differently!\n"); */ /* changed as per Jonathan's comment. */
printf("'%s' does not appear in '%s'.\n", ss, sg);
}
}
}

此解决方案没有考虑到较短的字符串可能会在较长的字符串中出现多次。它总是通知第一次出现。

关于c - 在 c 中比较不相等的 char 数组的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17000213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com