📜  查找字符串中字符的字母顺序之和

📅  最后修改于: 2022-05-13 01:56:06.035000             🧑  作者: Mango

查找字符串中字符的字母顺序之和

给定大小为N的字符串S ,任务是找出给定字符串中每个字符的字母值之和。

例子:

方法:

  • 遍历给定字符串S 中存在的所有字符。
  • 对于每个小写字符,将值(S[i] – 'a' + 1)添加到最终答案,或者如果它是大写字符,将(S[i] – 'A' + 1)添加到最终答案.

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
int findTheSum(string alpha)
{
    // Stores the sum of order of values
    int score = 0;
 
    for (int i = 0; i < alpha.length(); i++)
    {
        // Find the score
        if (alpha[i] >= 'A' && alpha[i] <= 'Z')
            score += alpha[i] - 'A' + 1;
        else
            score += alpha[i] - 'a' + 1;
    }
    // Return the resultant sum
    return score;
}
 
// Driver Code
int main()
{
    string S = "GeeksforGeeks";
    cout << findTheSum(S);
    return 0;
}


Java
// Java code to implement the above approach
import java.util.*;
public class GFG
{
     
static int findTheSum(String alpha)
{
   
    // Stores the sum of order of values
    int score = 0;
 
    for (int i = 0; i < alpha.length(); i++)
    {
       
        // Find the score
        if (alpha.charAt(i) >= 'A' && alpha.charAt(i) <= 'Z')
            score += alpha.charAt(i) - 'A' + 1;
        else
            score += alpha.charAt(i) - 'a' + 1;
    }
   
    // Return the resultant sum
    return score;
}
 
// Driver code
public static void main(String args[])
{
    String S = "GeeksforGeeks";
    System.out.println(findTheSum(S));
}
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python3 program for the above approach
def findTheSum(alpha):
     
    # Stores the sum of order of values
    score = 0
 
    for i in range(0, len(alpha)):
 
        # Find the score
        if (ord(alpha[i]) >= ord('A') and ord(alpha[i]) <= ord('Z')):
            score += ord(alpha[i]) - ord('A') + 1
        else:
            score += ord(alpha[i]) - ord('a') + 1
 
    # Return the resultant sum
    return score
 
# Driver Code
if __name__ == "__main__":
 
    S = "GeeksforGeeks"
    print(findTheSum(S))
 
# This code is contributed by rakeshsahni


C#
// C# code to implement the above approach
using System;
class GFG
{
  static int findTheSum(string alpha)
  {
 
    // Stores the sum of order of values
    int score = 0;
 
    for (int i = 0; i < alpha.Length; i++)
    {
 
      // Find the score
      if (alpha[i] >= 'A' && alpha[i] <= 'Z')
        score += alpha[i] - 'A' + 1;
      else
        score += alpha[i] - 'a' + 1;
    }
 
    // Return the resultant sum
    return score;
  }
 
  // Driver code
  public static void Main()
  {
    string S = "GeeksforGeeks";
 
    Console.Write(findTheSum(S));
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
133