-2

I tried removing a particular word from a string, I end up getting an extra space in between other words. This is the code i used

String title = "Senior Account Manager Presidio Networke";
title = title.replace("Presidio","");

Output: Senior Account Manager " " Networke ,

I get an extra white space in between manager and networke

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Ashok Kumar
  • 393
  • 1
  • 7
  • 17
  • The original problem can be also solved using [this solution](https://stackoverflow.com/questions/2932392/java-how-to-replace-2-or-more-spaces-with-single-space-in-string-and-delete-lead). – Wiktor Stribiżew Apr 25 '18 at 13:14

3 Answers3

5

Capture all possible preceding and following whitespace, and then replace with a single space:

title = title.replaceAll("\\s+Presidio\\s+", " ").trim();

Note: The call to String#trim handles the edge cases where Presidio might appear as either the first or last word in the sentence. In this case, we don't even want a single space in the replacement, we want empty string.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

Do like this

title = title.replace(" Presidio","");
Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
0
private String removeWord(String unwanted, String sentence)
{
    StringTokenizer st = new StringTokenizer(sentence);
    String remainder = "";

    while(st.hasMoreTokens())
    {
        String temp = st.nextToken();

        if(!temp.equals(unwanted))
        {
            remainder += temp + " ";
        }
    }
    return remainder.trim();
}

Use the Class();

Lit
  • 116
  • 5