2
for(i = 0; str[i]; ++i)
    ++count[str[i]];

// Change count[i] so that count[i] now contains actual position of
// this character in output array
for (i = 1; i <= RANGE; ++i)
    count[i] += count[i-1];

// Build the output character array
for (i = 0; str[i]; ++i)
{
    output[count[str[i]]-1] = str[i];
    --count[str[i]];
}

通常循环的中间部分for有一些比较,但for这里的第一个循环只有一个表达式。你能告诉我那是什么吗?

4

3 回答 3

5

在 C 中,任何表达式都可以被评估为“真”。在这种情况下,我们正在检查是否str[i]为真。如果是'\0',那么它是假的并且循环结束 - 这样我们一旦找到字符串的结尾就可以离开循环。任何其他字符值都被视为真,循环继续。

于 2013-09-20T14:19:28.343 回答
3

str[i]相当于写str[i] != 0

于 2013-09-20T14:20:16.560 回答
3

for循环为第二个参数接受一个表达式(比较也是一个表达式)。如果它的值不为零,则表达式将产生“真”。

如您所知,C 中的字符串以NUL字符结尾(值为0),因此

for(i = 0; str[i]; ++i)
    ++count[str[i]];

真正意思:

对于字符串的每个字符(从起始字符 - 以 0 为索引,直到 NUL 字符到达),递增计数数组中的相应字段。

于 2013-09-20T14:25:51.087 回答