I have Written a String "I am good 2017 Girl ". i need to remove "2017 Girl" without using replace method.
Output:
I am good
I have Written a String "I am good 2017 Girl ". i need to remove "2017 Girl" without using replace method.
Output:
I am good
Assuming that you use Java 8, you could do that using the Stream API, by using the literal "2017 Girl" as separator pattern and by using Collectors.joining() as collector to build a new String without any occurence of the provided pattern:
String result = Pattern.compile("2017 Girl", Pattern.LITERAL)
.splitAsStream("I am good 2017 Girl ")
.collect(Collectors.joining());
indexOf and substring (like what you propose ) is finally much more error prone, so I finally I decided to provide this clear and short answer.You can do something like:
String initialInput = "I am a good 2017 girl";
String searchFor = "2017 girl";
int indexOfSearch = intialInput.indexOf(searchFor);
String reworkedInput = initialInput.substring(0, indexOfSearch);
More wordy as the stream solution, but also more basic.
Notes: the above is meant as inspiration to get you going. "Real" code should for example check the computed index to be > 0; to ensure that the substring call doesn't fail. You also want to read the javadoc for substring() to understand what it does and will return.
You can use the substring method:
public static String remove(String base, String toRemove) {
if (base == null) return null;
if (toRemove == null) return base;
int start = base.indexOf(toRemove);
if (start < 0) return base;
String suffix = base.substring(start + toRemove.length());
if (start > 0)
return base.substring(0, start - 1) + suffix;
else
return suffix;
}
basically, you search for the position of the string to remove, and then concat the prefix and suffix strings (the parts before and after the substring to be removed).
This solution removes the string only once. If it is repeated, and you want to remove all the instances, you can quickly modify this to do that, doing the same on the suffix (recursively).