[英]the purpose of the middle part of for loop
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
循環這里只有一個表達式。 你能告訴我那是什么意思嗎?
在C中,任何表達式都可以評估為“真值”。 在這種情況下,我們檢查str[i]
是否為真。 如果它是'\\0'
,那么它是假的並且循環結束 - 這樣我們就可以在找到字符串的結尾后離開循環。 任何其他字符值都被視為true,循環繼續。
str[i]
相當於寫str[i] != 0
for
循環為第二個參數提供表達式(比較也是一個表達式)。 如果表達式的值不為零,則表達式將產生“真”。
您可能知道,C中的字符串以NUL
字符(值為0
)終止,因此
for(i = 0; str[i]; ++i)
++count[str[i]];
真正意思:
對於字符串的每個字符(從起始字符開始 - 索引為0,直到NUL字符到達),遞增計數數組中的相應字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.