I am trying to write a generic java method wherein I want to remove a part of a String after a particular character and till a particular character. For e.g. "My name is-A" is the String, then I want a method that should remove String till – or remove String after -. So my expected output here would be "My name is-" or "A". Below is my code.
String p="Free Float Factor-FFF";
char[] s2= p.toCharArray();
char[] s3;
int i=0;
do {
s3=ArrayUtils.remove(s2, i);
i++;
}while((!s2.equals("-"))&&i<s2.length);
System.out.println(new String(s3));
}
The output I am getting here is Free Float Factor-FF I want either "Free Float Factor-" or "FFF" as the output. I am trying to convert the String into an array and then remove the part of the String till – but it is removing the last character. Slightly confused by this.
>Solution :
It’s unclear how you would decide whether to return the bit before or the bit after. But you can get those two parts using indexOf to find the character, and then use substring to get the portion of the string:
int pos = p.indexOf('-');
String before = p.substring(0, pos);
String after = p.substring(pos+1);