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

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

本文关键字:英文字母 位置 相对于 字符 何知道 字符串      更新时间:2023-10-16

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

word="Bag"

我需要输出为:

B-2 A-1 七国集团

这是一个更便携的解决方案:

只有 26 个字母需要考虑,因此只需提供一个查找表即可轻松回答您的问题。 无需调用诸如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 
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'