我如何知道字符串中字符相对于英文字母的位置值?
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 七国集团
这是一个更便携的解决方案:
只有 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'
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 输入中的字符串数未知(以字母表示)
- 将数字转换为字母(例如:123 转换为一二三)
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 如何定义更改car类中car位置的方法
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 我如何知道字符串中字符相对于英文字母的位置值?
- 如何训练svm对英文字母图像进行分类
- C++在第4个位置插入一个字母
- 如何在 c++ 中打印字母和符号后保留在一个位置
- 我如何在常数时间(O(1))内获得字母表(1-26)中字符的数值/位置,而不使用任何内置方法或函数
- visual studio-C++在英文Windows中处理西里尔字母字符串
- 我如何打印4个不同字母组合成2个字母对的所有方式来填充4个位置,每个字母正好出现两次