0

I have Written a String "I am good 2017 Girl ". i need to remove "2017 Girl" without using replace method.

Output:

I am good
1
  • If there is an answer below that fulfills your requirements consider accepting it otherwise improve your question to indicate what's wrong and/or missing Commented Jan 24, 2017 at 7:27

3 Answers 3

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Nice idea; but not exactly the thing I would suggest to a beginner ;-)
@GhostCat I agree but I realized that providing something that could sound like "more appropriate" based on 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.
1

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.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.