例如,如果我有类似的东西:
word="Bag"
我需要输出为:
B-21一g-7
我希望以下代码段对您有所帮助:
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'
for (char ch: word) {
cout << ch << "-" << (tolower(ch) - '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
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