Reputation: 83
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
Upvotes: 0
Views: 694
Reputation: 124215
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
" /"
, " /"
, "/ "
, "/ "
, " / "
, " / "
It will also match single /
but replacing it with same /
shouldn't cause any problem.
Upvotes: 4