函数接受两个字符串,想要比较第n个字符

时间:2011-04-16 03:04:03

标签: c

我有一个函数,它接受两个字符串,我想,比方说比较每个字符串的第二个字母到另一个字符串。 我该如何解决这个问题:

if (strncmp(str1 + 1, str2 + 1) != 0) {
...

我收到一条错误,指出传递参数会产生一个没有强制转换的整数的指针。

2 个答案:

答案 0 :(得分:3)

if (str1[1] == str2[1]) {
    /* Do something */
}

答案 1 :(得分:0)

如果您想允许任何字符串小于您想要比较的位置:

/* Return 1 if s1[n] > s2[n], 0 if s1[n] == s2[n], -1 if s1[n] < s2[n].
   Return -2 if any of the strings is smaller than n bytes long. */
int compare_nth(const char *s1, const char *s2, size_t n)
{
    size_t i;

    for (i=0; i < n; ++i)
        if (s1[i] == 0 || s2[i] == 0)
            return -2;

    if (s1[n] < s2[n])
        return -1;
    else if (s1[n] > s2[n])
        return 1;
    else
        return 0;
}

然后,要在n个字符相等时执行某些操作,您可以执行以下操作:

if (compare_nth(s1, s2, n) == 0) {
    /* do whatever you want to do here */
}

如果您确定每个字符串中至少有n个字符,您可以按照其他人的说法进行操作:

if (s1[n] == s2[n]) {
    /* do whatever you want to do here */
}

(注意:由于C中的索引是从0开始,n在这里使用的意思相同。所以,为了测试第二个字符,n将是1。)< / p>