给定字符串英文字母。任务是为字符串的每个字符在英文字母中打印其位置。
注意:字符串中的字符不区分大小写。也就是说,“ A”和“ a”都处于第一位置。
例子:
Input: “Geeks”
Output: 7 5 5 11 19
‘G’ is the 7th character of the alphabets
‘e’ is the 5th and so on…
Input: “Algorithms”
Output: 1 12 7 15 18 9 20 8 13 19
方法:
通过对数字31进行逻辑与运算,可以轻松找到字母在字母表中的位置。
请注意,这仅适用于字母,不适用于特殊字符。
每个字母都有一个ASCII值,可以用二进制形式表示。用数字31按位执行此值,将得出字母在字母表中的位置。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
const int NUM = 31;
// Function to calculate the position
// of characters
void positions(string str, int n)
{
for (int i = 0; i < n; i++) {
// Performing AND operation
// with number 31
cout << (str[i] & NUM) << " ";
}
}
// Driver code
int main()
{
string str = "Geeks";
int n = str.length();
positions(str, n);
return 0;
}
Java
// Java implementation of the approach
public class GFG {
public static final int NUM = 31;
// Function to calculate the position
// of characters
static void positions(String str, int n)
{
for (int i = 0; i < n; i++) {
// Performing AND operation
// with number 31
System.out.print((str.charAt(i) & NUM) + " ");
}
}
// Driver code
public static void main(String[] args)
{
String str = "Geeks";
int n = str.length();
positions(str, n);
}
}
Python
# Python3 implementation of the approach
NUM = 31
# Function to calculate the position
# of characters
def positions(str):
for i in str:
# Performing AND operation
# with number 31
print((ord(i) & NUM), end =" ")
# Driver code
str = "Geeks"
positions(str)
C#
// C# implementation of the approach
using System;
class GFG {
public static int NUM = 31;
// Function to calculate the position
// of characters
static void positions(string str, int n)
{
for (int i = 0; i < n; i++) {
// Performing AND operation
// with number 31
Console.Write((str[i] & NUM) + " ");
}
}
// Driver code
public static void Main()
{
string str = "Geeks";
int n = str.Length;
positions(str, n);
}
}
// This code is contributed by AnkitRai01
PHP
输出:
7 5 5 11 19