2

I’m using the .replace method to remove a character in a string. The issue I’m having is I’m using the parameters

.replace("#", "")

To remove the hashtag from a string that could be for example “# hello” The replace method is doing what I want in removing the hashtag however it leaves an actual blank space in the string when I use it. So “# hello” becomes “ hello” when really I want it to be “hello”. Is there a different method I can use or a different parameter I can use to achieve what I want?

khelwood
  • 55,782
  • 14
  • 81
  • 108
alwaysStuckJava
  • 359
  • 1
  • 3
  • 10

2 Answers2

5

Using regex

System.out.println("a # b c".replaceAll("#\\s*", ""));

This replaces # and optionaly some whitespace with nothing, so it outputs:

a b c

Regex 101 - Removes the highlighted sections

jrtapsell
  • 6,719
  • 1
  • 26
  • 49
1

Here is an example:

String string1 = "  #  WordIWantToKeep  ";//Blank spaces before and after
//Using the same variable
string1 = string1.replace("#", "").trim();

OUTPUT → "WordIwantToKeep" .trim() removes all blanks at the beginning and end of the string

It's important the order of the .replace() and .trim(). I recomend you to test this 2 different options, and see the output

string1 = string1.replace("#", "").trim();//Right answer for your post

OUTPUT → "WordIwantToKeep"

string1 = string1.trim().replace("#", "");

OUTPUT → " WordIwantToKeep"

But the way sorry if my english level isn't good enough.

rencinas
  • 142
  • 1
  • 8