使用C ++中的位运算查找字母在Alphabet中的位置
在这个问题中,我们给了一个由英文字母组成的字符串str。我们的任务是使用位操作找到字母在字母表中的位置。
问题描述: 在这里,我们将以英文字母的形式返回字符串中每个字符的位置。
字符串的字符不区分大小写,即“t”和“T”被视为相同。
让我们举个例子来了解这个问题,
输入: str=“Nhooo”
输出: 2021201518911219161591420
解决方法
查找字符位置的一种简单解决方案是使用31查找其逻辑AND运算。
该程序说明了我们解决方案的工作原理,
示例
#include <iostream> using namespace std; void findLetterPosition(string str, int n) { for (int i = 0; i < n; i++) { cout<<(str[i] & 31) << " "; } } int main() { string str = "nhooo"; int n = str.length(); cout<<"字符串中的字母位置 "<<str<<" is \n"; findLetterPosition(str, n); return 0; }输出结果
字符串中的字母位置 nhooo is 20 21 20 15 18 9 1 12 19 16 15 9 14 20