我如何知道字符串中字符相对于英文字母的位置值?

How do I know the positional value of a character in a string with respect to that of the English alphabets?

例如,如果我有类似的东西:

word="Bag"

我需要输出为:

B-2 a-1 g-7

for (char ch: word) {
    cout << ch << "-" << (tolower(ch) - 'a' + 1) << " ";
}

希望以下代码片段对您有所帮助:

char c = 'g';  //your character here

int position = 1 + (tolower(c))-'a': //ensure that character is in lowercase and find its position relative to 'a'

这里有一个更适合table的解决方案:

只有 26 个字母需要考虑,因此您的问题只需提供一个查询就可以轻松回答 table。无需调用 tolower 等函数,也无需假设字母在整理顺序中是连续的(因为 EBCDIC 不遵循此模式):

#include <iostream>
#include <unordered_map>
#include <string>

int main()
{
   // Create the lookup table -- this could have been done in many ways,
   // such as a static table of characters to values, but I chose a simple
   // literal string and build the table at runtime.

   const char *alpha = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
   std::unordered_map<char, int> cMap;
   for (int i = 0; i < 52; ++i)
       cMap[alpha[i]] = i / 2;  // Note there are two characters per character value, 
                                // the lower and the upper case version of the character

   // Test
   std::string test = "Bag";
   for ( auto& c : test)
      std::cout << c << '-' << cMap[c]+1 << ' ';
   std::cout << '\n';

   test = "Buy";
   for ( auto& c : test)
      std::cout << c << '-' << cMap[c]+1 << ' ';
   std::cout << '\n';

   test = "Elephant";
   for ( auto& c : test)
      std::cout << c << '-' << cMap[c]+1 << ' ';
}

输出:

B-2 a-1 g-7 
B-2 u-21 y-25 
E-5 l-12 e-5 p-16 h-8 a-1 n-14 t-20