I have a string like foo..txt and I want to convert it to foo.txt
The occurence of ‘.’ may be more than 2 also.
What is the best way to accomplish this?
edit : The ‘.’ may not occur just together. The occurences may be as below too
foo.bar.txt = foo bar.txt
foo..bar.foo.txt = foo bar.txt
I believe what you want is to replace all periods in the file name part with spaces, but keep the extension, right?
If so, something like this would be appropriate:
Essentially the way this works is:
lastIndexOf('.')in our stringk, then we have logically separated our string into:substring(0, k), the prefix partsubstring(k), the suffix (file extension) partreplaceAllmatches of\.+with" "\., repeated one or more times+trim()this string to remove leading and trailing spacesClarifications
\.+instead of.+is because the dot.is a regex metacharacter, but in this case we really mean a literal period, so it needs to be escaped as\."\\.+"is because\is itself a Java string literal escape character. For example, the string literal"\t"contains the tab character. Analogously, the string literal"\\"contains the backslash character; it has alength()of one.References
String API:lastIndexOfandtrim()