Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Write a program to accept a sentence and count and print number of consecutive letter pairs that exists.

0 votes

Eg:        “IT WAS NOT TOUGH FOR HIM TO RESIDE ABOVE THE HILL”
output:  Number of consecutive pair of characters: 6
consecutive pair:  NO GH IM DE AB HI

asked by kamalktg (5 points)

1 Answer

0 votes

Use a loop to iterate through the characters. In each iteration of the loop, get the current character and the next character. If the value of nextChar is currentChar + 1 (ASCII values of the characters are considered when we add 1 and compare the characters), then they are consecutive.

Program

import java.util.Scanner;

public class ConsecutiveLetters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter sentence: ");
        String s = scanner.nextLine();
        int result = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            char currentChar = s.charAt(i);
            char nextChar = s.charAt(i + 1);
            if (nextChar == currentChar + 1) {
                result++;
            }
        }
        System.out.println("Number of consecutive characters are " + result);
    }
}

Sample output

Enter sentence: IT WAS NOT TOUGH FOR HIM TO RESIDE ABOVE THE HILL
Number of consecutive characters are 6

 

answered by Ranjith (2,683 points)
...