Open In App

Count characters at same position as in English alphabet

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string of lower and uppercase characters, the task is to find how many characters are in the same position as in the English alphabet.

Examples: 

Input:  ABcED 
Output :  3
First three characters are at same position
as in English alphabets.

Input:  geeksforgeeks 
Output :  1
Only 'f' is at same position as in English
alphabet

Input :  alphabetical 
Output :  3

For this we can have simple approach: 

1) Initialize result as 0.
2) Traverse input string and do following for every 
   character str[i]
     a) If 'i' is same as str[i] - 'a' or same as 
        str[i] - 'A', then do result++
3) Return result

Implementation:

C++




// C++ program to find number of characters at same
// position as in English alphabets
#include<bits/stdc++.h>
using namespace std;
 
int findCount(string str)
{
    int result = 0;
 
    // Traverse input string
    for (int i = 0 ; i < str.size(); i++)
 
        // Check that index of characters of string is
        // same as of English alphabets by using ASCII
        // values and the fact that all lower case
        // alphabetic characters come together in same
        // order in ASCII table.  And same is true for
        // upper case.
        if (i == (str[i] - 'a') || i == (str[i] - 'A'))
            result++;
 
 
    return result;
}
 
// Driver code
int main()
{
    string str = "AbgdeF";
    cout << findCount(str);
    return 0;
}


Java




// Java program to find number of
// characters at same position
// as in English alphabets
import java.io.*;
class GFG
{
 
    static int findCount(String str)
    {
        int result = 0;
 
        // Traverse input string
        for (int i = 0; i < str.length(); i++)
         
        // Check that index of characters
        // of string is same as of English
        // alphabets by using ASCII values
        // and the fact that all lower case
        // alphabetic characters come together
        // in same order in ASCII table. And
        // same is true for upper case.
        {
            if (i == (str.charAt(i) - 'a')
                    || i == (str.charAt(i) - 'A'))
            {
                result++;
            }
        }
        return result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "AbgdeF";
        System.out.print(findCount(str));
    }
}
 
// This code is contributed by Rajput-JI


Python3




# Python program to find number of
# characters at same position as
# in English alphabets
 
# Function to count the number of
# characters at same position as
# in English alphabets
def findCount(str):
    result = 0
 
    # Traverse the input string
    for i in range(len(str)):
 
        # Check that index of characters of string is
        # same as of English alphabets by using ASCII
        # values and the fact that all lower case
        # alphabetic characters come together in same
        # order in ASCII table. And same is true for
        # upper case.
        if ((i == ord(str[i]) - ord('a')) or
            (i == ord(str[i]) - ord('A'))):
            result += 1
    return result
 
# Driver Code
str = 'AbgdeF'
print(findCount(str))
 
# This code is contributed
# by SamyuktaSHegde


Javascript




<script>
      // JavaScript program to find number of characters at same
      // position as in English alphabets
 
      function findCount(str) {
        var result = 0;
 
        // Traverse input string
        for (var i = 0; i < str.length; i++)
          // Check that index of characters of string is
          // same as of English alphabets by using ASCII
          // values and the fact that all lower case
          // alphabetic characters come together in same
          // order in ASCII table. And same is true for
          // upper case.
          if (
            i === str[i].charCodeAt(0) - "a".charCodeAt(0) ||
            i === str[i].charCodeAt(0) - "A".charCodeAt(0)
          )
            result++;
 
        return result;
      }
 
      // Driver code
      var str = "AbgdeF";
      document.write(findCount(str));
    </script>


C#




// C# program to find number of
// characters at same position
// as in English alphabets
using System;
 
class GFG
{
static int findCount(string str)
{
    int result = 0;
 
    // Traverse input string
    for (int i = 0 ; i < str.Length; i++)
 
        // Check that index of characters
        // of string is same as of English
        // alphabets by using ASCII values
        // and the fact that all lower case
        // alphabetic characters come together
        // in same order in ASCII table. And
        // same is true for upper case.
        if (i == (str[i] - 'a') ||
            i == (str[i] - 'A'))
            result++;
 
    return result;
}
 
// Driver code
public static void Main()
{
    string str = "AbgdeF";
    Console.Write(findCount(str));
}
}
 
// This code is contributed
// by Akanksha Rai


PHP




<?php
// PHP program to find number of
// characters at same position as
// in English alphabets
 
// Function to count the number of
// characters at same position as
// in English alphabets
function findCount($str)
{
    $result = 0;
 
    // Traverse the input string
    for ($i = 0; $i < strlen($str); $i++)
    {
 
        // Check that index of characters of string is
        // same as of English alphabets by using ASCII
        // values and the fact that all lower case
        // alphabetic characters come together in same
        // order in ASCII table. And same is true for
        // upper case.
        if (($i == ord($str[$i]) - ord('a')) or
            ($i == ord($str[$i]) - ord('A')))
            $result += 1;
    }
    return $result;
}
 
// Driver Code
$str = "AbgdeF";
print(findCount($str))
 
// This code has been contributed by 29AjayKumar
?>


Output

5

Time Complexity: O(N), where N is the length of string.
Auxiliary Space: O(1).

Approach: Same Position Character Counter

  1. Initialize a counter variable to 0 to count the number of characters in the same position as in the English alphabet.
  2. Loop through each character in the input string.
  3. Convert the character to lowercase using the lower() method.
  4. Get the ASCII code of the character using the ord() method.
  5. Subtract the ASCII code of ‘a’ from the ASCII code of the character to get its position in the alphabet (0-indexed).
  6. Compare the position of the character with its index in the input string. If they are equal, increment the counter variable.
  7. Return the counter variable as the output.

C++




#include <iostream>
#include <string>
using namespace std;
 
int count_same_position_chars(string s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = tolower(s[i]);
        if (c - 'a' == i) {
            count++;
        }
    }
    return count;
}
 
int main() {
    string input_string = "ABcED";
    int result = count_same_position_chars(input_string);
    cout << result << endl; // Output: 3
    return 0;
}


Java




import java.util.Scanner;
 
public class Main {
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        String inputString = "ABcED";
        int result = countSamePositionChars(inputString);
        System.out.println(result); // Output: 3
    }
 
    public static int countSamePositionChars(String s)
    {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = Character.toLowerCase(s.charAt(i));
            if (c - 'a' == i) {
                count++;
            }
        }
        return count;
    }
}


Python3




def count_same_position_chars(s):
    count = 0
    for i, c in enumerate(s):
        c = c.lower()
        if ord(c) - ord('a') == i:
            count += 1
    return count
 
# Example usage:
input_string = "ABcED"
result = count_same_position_chars(input_string)
print(result)  # Output: 3
 
#This is contributed by Uppala Sridevi


C#




// C# code addition
 
using System;
 
class Program {
     
  // Driver code
  static void Main(string[] args) {
    string inputString = "ABcED";
    int result = CountSamePositionChars(inputString);
    Console.WriteLine(result); // Output: 3
  }
 
 
  static int CountSamePositionChars(string s) {
    int count = 0;
    for (int i = 0; i < s.Length; i++) {
         
      // Convert each character to lower case character.
      char c = Char.ToLower(s[i]);
         
      // c-'a' means subtracting ASCII value from c, and
      // converting it into 0-based indexing.
      if (c - 'a' == i) {
        count++;
      }
    }
    return count;
  }
}
 
// The code is contributed by Arushi Goel.


Javascript




function CountSamePositionChars(s) {
  let count = 0;
  for (let i = 0; i < s.length; i++) {
         
    // Convert each character to lower case character.
    let c = s[i].toLowerCase();
         
    // c-'a' means subtracting ASCII value from c, and
    // converting it into 0-based indexing.
    if (c.charCodeAt(0) - 'a'.charCodeAt(0) == i) {
      count++;
    }
  }
  return count;
}
 
let inputString = "ABcED";
let result = CountSamePositionChars(inputString);
console.log(result); // Output: 3


Output

3

Time complexity: O(n), where n is the length of the input string.

Auxiliary space: O(1), as we are only using a constant amount of extra space to store the counter variable and temporary variables.



Last Updated : 20 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads