s_i = s [i] - ' a'是什么意思?

时间:2016-05-13 06:27:11

标签: c++

void main()
{
string s, Letter;
cin >> s;
int count[26], i, s_i; 
for (i = 0; i < 26; i++)
    count[i] = 0;
int n = sizeof(s);
for (i = 0; i < n; i++)
{
    s_i = s[i] - 'a';
    count[s_i]++; 
}
for (i = 0; i < 26; i++)
{
    if (count[i] != 0)
    {
        Letter = 'a' + i;
        cout << Letter << " : " << count[i] << endl;
    }
}
}

这是一个计算字符串数量的程序。 s_i = s [i] - &#39; a&#39;是什么意思? ?特别是,为什么要使用 - &#39; a&#39;?还有其他方法来计算信件吗?

2 个答案:

答案 0 :(得分:1)

表达式x - 'a'为您提供x中的字符值与字母表的第一个小写字母之间的距离。

例如:
'b' - 'a'== 1
'c' - 'a'== 2

编辑1:更简单的方法
声明您的计数数组有256个插槽 使用该字符作为数组的索引 增加索引处的值。

例如:

unsigned int counts[256];
char c = 'b';
//...
counts[c] += 1;

使用减法,x - 'a'允许更小的数组。

编辑2:更便携的解决方案
更便携的解决方案,不依赖于编码,是使用包含字母表的字符数组。搜索字符,如果找到,则索引是字符的偏移量。

char c = 'j';
const std::string lowercase_alphabet = "abcdefghijklmnopqrstuvwxyz";
const std::string uppercase_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned int counts[26] = {0};
//...
unsigned int index = lowercase_alphabet.find(c);
if (index != std::string::npos)
{
    ++counts[index];
}
else
{
  index = uppercase_alphabet.find(c);
  if (index != std::string::npos)
  {
    ++counts[index];
  }
}

相同的概念可以应用于字符数组而不是std::string类型。

注意:touppertolower函数不用于避免本地化开销。

答案 1 :(得分:0)

几点需要注意:

  1. 该程序假定字符串仅包含LowerCase字母(a-z),而不包含任何其他内容。因此,26 possible character

  2. 最多可以[a-z]
  3. 通过执行-'a',我们只是从'a'中减去s[i]的ascii值。每个字符都有一个唯一的ascii value。在编译期间,编译器检查'a'的ascii值,并用-'a'替换-48。我们可以完成-'a'而不是-48,但在这种情况下,我们不需要记住'a'的ascii值。

  4. [a-z]的所有ascii值都是连续的。 a's值为48,z's值为57.因此,通过s[i]-'a',我们可以了解ith varaiblea之间的区别。< / p>

  5. 最后Letter = 'a' + i;完成了原始角色。

相关问题