• Post Reply Bookmark Topic Watch Topic
  • New Topic

Remove extra spaces from a given string  RSS feed

 
dhrubo bhattacharjee
Greenhorn
Posts: 23
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone, I was recently looking at the programming questions asked in interview from glassdoor and there I found a problem to remove extra spaces from a given String.
For example if the input is  then the Output will be

I have tried implementing the following solution which only works partially:


This works fine for the given input and giving me the output as but however if I try the following input then I am getting the output as with a leading space. Can anyone give any suggestions about how can I take care of the leading spaces.It will be really helpful if you anyone can give me a suggestion or a hint instead of the code as I am quite new to Java and using your hints/suggestions and implementing it myself will help me get better at it.
Thanks
 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First off, you can remove leading and trailing spaces with String.trim().

Secondly, your string concatenation "works" but is very inefficient. I suggest you look into the StringBuilder class and its append() method. Your output = output + ""; doesn't do anything and could have been omitted entirely.

Your approach works so you might want to leave it alone, on the other hand, you could have used String.replaceAll() to do the same thing but you would need to give it a regular expression pattern that would match one or more spaces.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dhrubo bhattacharjee wrote:. . . if I try the following input then I am getting the output as with a leading space. . . .
That is actually the correct result if you replace all multiple spaces by single spaces; as CB has suggested, removing leading and trailing spaces is a different task. It all depends how the problem is specified. I would have thought you get a trailing space in that particular output, too. You are missing that because a plain simple println instruction doesn't show you the end of the text printed.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try changing the print statement to read:-That will add quote marks so you can see the trailing spaces.
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check what happens if the original string does not end with a space.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!