-2

I am getting this string from Db

str = "External - Internal ";

I want to remove the last whitespace from the string. I have already tried string.trim() and assigned it to another string Kindly suggest as this is just not working. below is my code for reference.

 public static void main(String args[]){
      String str = "External - Internal ";

      String temp = str.trim();
      System.out.println("1"+temp);
      temp=str.replaceAll(" ", "");
      System.out.println("2"+temp);
      temp=str.replace("\\r", "");
      System.out.println("3"+temp);
   }

Regards Abhi

aliteralmind
  • 19,847
  • 17
  • 77
  • 108

2 Answers2

0

You could do this simply through string.replaceAll or string.replaceFirst function.

string.replaceAll("\\s(?=\\S*$)", "");

If you exactly mean the space which was at the end then use the below regex.

string.replaceAll("\\s$", "");

Use \\s+ instead of \\s if you want to deal with one or more spaces.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • or `string.replaceFirst("\\s(?=\\S*$)", "");` – Avinash Raj Mar 23 '15 at 12:51
  • Thanks All for your promt response, – user4703055 Mar 23 '15 at 13:30
  • just want to confirm replaceAll("\\s(?=\\S*$)", "") if it removes only the whitespaces at the end. Please confirm – user4703055 Mar 23 '15 at 13:31
  • yep, it removes the last whitespace ie, in this input `foo bar bux`, this would also remove the space before `bux`. If you want to remove the space which was at the end, then use `\\s$` – Avinash Raj Mar 23 '15 at 13:34
  • tried both the options suggested by you, but space is not removed. kindly suggest – user4703055 Mar 23 '15 at 13:39
  • it works for me. Just assign the result to another variable and then print that variable. – Avinash Raj Mar 23 '15 at 13:40
  • Surprising how it is working with trim, as even I tried assigning it to another variable, I have found a way to handle it, but still looking for a neat way of doing this. – user4703055 Mar 23 '15 at 14:19
  • try `string.replaceAll(" (?=\\S*$)", "");` – Avinash Raj Mar 23 '15 at 14:21
  • I am using below code for now public static void main(String args[]){ String str = "External - Internal "; System.out.println("+"+str.substring(str.length()-1)); if(str.substring(str.length()-1).equals(" ")){ str = str.replace(str.substring(str.length()-1), ""); System.out.println(""+str); } } – user4703055 Mar 23 '15 at 14:21
0

You can find your answer here Strip Leading and Trailing Spaces From Java String

Look at the top two answers. Try right trim as myString.replaceAll("\s+$", "");

Community
  • 1
  • 1
Abdul Rehman Yawar Khan
  • 1,088
  • 3
  • 17
  • 40
  • already tried it, not working in case of my string, I suspect it is normal space, so given a try for carriage return and tabs but that too not giving expected result :( – user4703055 Mar 23 '15 at 13:57