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));
}
}
System.out.println("The processed string is "+sb.toString());
}
}
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Enter the string"<<endl;
cin>>str;
string str1="";
for(int i=0;i<str.length();i++)
{
if(i==0)
{
//sauravhathi
str1+=str[i];
}
else if(str[i]==str[i-1])
{
str1+="*";
str1+=str[i];
}
else
{
//sauravhathi
str1+=str[i];
}
}
cout<<"The processed string is "<<str1<<endl;
return 0;
}
print("Enter the string")
str=input()
str1=""
for i in range(len(str)):
if i==0:
str1+=str[i]
elif str[i]==str[i-1]:
str1+="*"
# sauravhathi
str1+=str[i]
else:
str1+=str[i]
print("The processed string is "+str1)
Happy Learning – If you require any further information, feel free to contact me.