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.
![[Solved] Adjacent characters with Java [Solved] Adjacent characters with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Adjacent-characters-with-Java.png)
![[Solved] YODA String with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-YODA-String-with-Java-300x200.png)
![[Solved] Detecting Palindromes String with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Detecting-Palindromes-String-with-Java-300x200.png)
