Logo

Programming-Idioms

  • Java
  • Python
  • Perl

Idiom #151 Remove string trailing path separator

Remove last character from string p, if this character is the file path separator of current platform.

Note that this also transforms unix root path "/" into the empty string!

use File::Spec qw();
chomp $p, File::Spec->catdir('');
import static java.io.File.separatorChar;
int n = p.length() - 1;
while (n != 0 && p.charAt(n) == separatorChar)
    p = p.substring(0, n--);
import os
if p.endswith(os.sep):
    p = p[:-1]
using System.IO;
p.TrimEnd(Path.DirectorySeparatorChar);

New implementation...
< >
programming-idioms.org