'remove characters before and after character in java
I need to delete all characters before and after a specific character using java programming for example:
input: ab*cd output:ad
input: ab**cd output:ad
import java.util.Scanner;
public class Starstring {
public static void main(String[] args) {
String str1;
String res="";
int n,i=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
str1=sc.next();
res=str1;
StringBuffer a = new StringBuffer(str1);
n=str1.length()-1;
for(i=0;i<n;i++)
{
if(str1.charAt(i)=='*')
{
res=a.delete(i-1, i+2).toString();
}
}
System.out.println("The final string is"+res);
}
}
I am getting expected output for case 1 but case 2 wrong output with ac as output.I don't know where I am going wrong.Someone please help me.Thanks in advance:)
Solution 1:[1]
You can use regex to replace character group in your string. To remove * and 1 character before & after it:
Pattern pt = Pattern.compile(".\\*+.");
Matcher match = pt.matcher(input);
String output = match.replaceAll("");
//System.out.println(output);
Solution 2:[2]
You can do it like this :
String str1;
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
str1=sc.next();
sc.close();
StringBuffer a = new StringBuffer(str1);
n=a.length();
for(int i=0;i<n;i++)
{
if(str1.charAt(i)=='*')
{
int aa = i-1;
int bb = i+1;
for(;bb<n; bb++){
if(str1.charAt(bb)!='*'){
break;
}
}
a.delete( aa, bb+1 );
i = bb;
}
}
String res = a.toString();
System.out.println("The final string is"+res);
But a better java regex way is :
After reading value from scanner -
String res2 = str1.replaceAll( ".[\\*]+.", "" );
System.out.println("The final string is"+res2);
Solution 3:[3]
Using @Vasan regex.. below is the code.
public static void main(String[] args) {
String str1;
String res="";
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
str1=sc.next();
res=str1;
StringBuffer a = new StringBuffer(str1);
n=str1.length()-1;
String[] splitVal = str1.split(".\\*+.");
String newString ="";
for(int i=0; i<splitVal.length; i++){
newString = newString + splitVal[i];
}
System.out.println("The final string is "+newString);
}
Hope you understand.
Solution 4:[4]
Try this:
public static void main(String[] args) {
System.out.println("Enter the string");
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String[] separated = str1.split(".\\*+.");
String result = "";
for(String str : separated) {
result += str;
}
System.out.println(result);
}
Solution 5:[5]
what if input is : *abc* or ab*c*de
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nam Tran |
| Solution 2 | Mahendra |
| Solution 3 | Sh4m |
| Solution 4 | Vijaya Pandey |
| Solution 5 | Suri |
