這段代碼真的讓我困惑,它使用一些斯坦福圖書館爲Vector(數組)類。誰能告訴我int index = line [j] - 'a';
爲什麼 - 'a'的目的是什麼?在C++字符串上的算術
void countLetters(string filename)
{
Vector<int> result;
ifstream in2;
in2.open(filename.c_str());
if (in.fail()) Error("Couldn't read '" + filename + "'");
for (int i = 0; i < ALPHABETH_SIZE; i++)
{
result.add(0); // Must initialize contents of array
}
string line;
while (true)
{
getLine(in, line);
// Check that we got a line
if (in.fail()) break;
line = ConvertToLowerCase(line);
for (int j = 0; j < line.length(); j++)
{
int index = line [j] - 'a';
if (index >= 0 && index < ALPHABETH_SIZE)
{
int prevTotal = result[index];
result[index] = prevTotal +1;
}
}
}
}
的代碼的用途:
使用一個文件名,並打印字母表的每個字母出現在該文件的次數。由於要打印26個數字,CountLetters需要創建一個Vector。例如,如果文件是:
據推測,它會找到一個字母是多遠的字母,但並不總是成立。 – chris
整個代碼正在計算字母頻率。 'result ['c' - 'a']'是字符'c'出現在文件中的次數。 – irrelephant