[Solved] Adjacent characters with Java

Adjacent characters: Given a string, write a program to compute a new string where identical chars that are adjacent in the original string are separated from each other by a “*”

Input and Output Format:

Refer sample input and output for formatting specifications.

All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output :

Enter the string

hello

The processed string is hel*lo

Solution

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the string");
        String str = input.nextLine();
        //sauravhathi
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (i == 0) {
                sb.append(str.charAt(i));
            } else if (str.charAt(i) == str.charAt(i - 1)) {
                sb.append("*");
                       //sauravhathi
                sb.append(str.charAt(i));
            } else {
                       //sauravhathi
                sb.append(str.charAt(i));
            }

       //sauravhathi
        }
        System.out.println("The processed string is "+sb.toString());
    }
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

πŸ“Œ Nodejs and Android 😎
πŸ“Œ Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *