0

I have a string "parent/ child1/ child2". I want to output it as "parent/child1/child2" by removing the white spaces in between.

I am doing in following way. How can I do it using lambda expression?

String absoluteName = "";
for(String name : Parent.getNames.split("/")) {
    if(absoluteName.equals("")) {
       absoluteName = name.trim();
    } else {
       absoluteName += "/" + name.trim();
    }
}

Can't do it using .replaceAll("\\s+", "")) , as in my use case "parent / child1 / child2 " and "pa rent / ch ild1 /ch ild2 " are taken as 2 different values.

Input -> Output

parent / child1 / child2 -> parent/child1/child2

pa rent / ch ild1 / ch ild2 -> pa rent/ch ild1/ch ild2

Akshay Talathi
  • 83
  • 1
  • 2
  • 13

1 Answers1

4

You don't need lambdas here. Simply replace / and following space with only / like

str = str.replace("/ ", "/");

or if there can be more spaces after / which you want to get rid of

str = str.replaceAll("/\\s+", "/");

Update: If you want to remove all whitespaces surrounding / you can use

str = str.replaceAll("\\s*/\\s*", "/");

* quantifier allows \\s (whitespace) to appear zero or more times. This means which means "\\s*/\\s*" will match and replace parts like

  • " /", " /",
  • or "/ ", "/ ",
  • or combination of above cases " / ", " / "

It will also match single / but replacing it with same / shouldn't cause any problem.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • String "parent/ child1 / child2" can have multiple white spaces in between. – Akshay Talathi Jun 21 '17 at 20:39
  • @AkshayTalathi OK, but you don't tell us how you want to handle that situation. Do you want to remove them or some of them should not be removed? – Pshemo Jun 21 '17 at 20:41
  • if input is "parent / child1 / child2" or "pa rent / ch ild1 / ch ild2 ",I want to output it as "parent/child1/child2" or "pa rent/ch ild1/ch ild2". – Akshay Talathi Jun 21 '17 at 20:43
  • @RapidReaders if you don't really need regex use `replace` method instead of `replaceAll`. Both methods will replace all matches, only difference is support for regex syntax in `replaceAll` (which IMO should be renamed to `replaceRegex` to avoid this confusion). – Pshemo Jun 21 '17 at 20:50
  • Will it trim white spaces before parent and after child2? – Akshay Talathi Jun 21 '17 at 21:11
  • @AkshayTalathi No but based on your title you wanted to "remove whitespace in between the string" which kind of excludes whitespaces at start or end. But to remove them simply use `trim()` method before or after replacement. – Pshemo Jun 21 '17 at 21:15