我怎么知道一个字符串相对于英文字母的位置值?

问题描述 投票:0回答:3

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

word="Bag"

我需要输出为:

B-21一g-7

c++ ascii
3个回答
2
投票

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

char c='g';//your character here
int position = 1+(to_lower(c))-'a': //ensure that character is in lowercase and find its position relative to 'a'

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

0
投票

这里是一种更可移植的解决方案:

仅考虑26个字母,因此只需提供查找表即可轻松回答您的问题。无需调用诸如tolower之类的函数,也无需假设字母在整理序列中是连续的(因为EBCDIC不遵循此模式):

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

int main()
{
   // Create the lookup table -- this could have been done in many ways  
   const char *alpha = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
   std::unordered_map<char, int> cMap;
   for (int i = 0; i < 52; ++i)
       cMap[alpha[i]] = i / 2;

   // 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 
© www.soinside.com 2019 - 2024. All rights reserved.