I want to combine the strings "test/"
and "/go"
as "test/go"
.
How can I do that?
I want to combine the strings "test/"
and "/go"
as "test/go"
.
How can I do that?
Using only java.io.File
the easiest way is to do:
String combined_path = new File("test/", "/go").getPath();
FilenameUtils.normalize()
from Apache Commons IO does what you want.
example:
FilenameUtils.normalize("foo/" + "/bar");
returns the string "foo/bar"
Append both the strings and replace //
with /
as below
"test//go".replace("//", "/")
Output: test/go
String test = "test/";
String go = "/go";
String result = test + go.substring(1);
Supposed this is a question related to file names, than take a look at apache-commons-io and its FilenameUtils class
final String test = "test/";
final String go ="/go";
System.out.println(FilenameUtils.normalize(test + go));
output on windows:
test\go
The normalize method will do much more for you, e.g. change '/' to '\' on windows systems.
By the way congrat's to your reputation score by nearly just asking questions :-)
Here's a Guava method that joins an Iterable<String>
of items with a char
, after trimming all instances of this character from beginning and end of the items:
public static String joinWithChar(final Iterable<String> items,
final char joinChar){
final CharMatcher joinCharMatcher = CharMatcher.is(joinChar);
return Joiner.on('/').join(
Iterables.transform(items, new Function<String, String>(){
@Override
public String apply(final String input){
return joinCharMatcher.trimFrom(input);
}
}));
}
Usage:
System.out.println(joinWithChar(Arrays.asList("test/", "/go"), '/'));
Output:
test/go
This solution