Extract file extension: Difference between revisions

→‎{{header|Go}}: Adjusted code to the changed task description
m (→‎{{header|Haskell}}: Remove update header)
(→‎{{header|Go}}: Adjusted code to the changed task description)
Line 532:
<lang go>package main
 
import ("fmt"
"fmt"
"path"
)
 
// An exact copy of `path.Ext` from Go 1.4.2 for reference:
func Ext(path string) string {
for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- {
if path[i] == '.' {
return path[i:]
}
}
return ""
}
 
// A variation that handles the extra non-standard requirement
// that extensions shall only "consists of one or more letters or numbers".
//
// Note, instead of direct comparison with '0-9a-zA-Z' we could instead use:
// case !unicode.IsLetter(rune(b)) && !unicode.IsNumber(rune(b)):
// return ""
// even though this operates on bytes instead of Unicode code points (runes),
// it is still correct given the details of UTF-8 encoding.
func ext(path string) string {
for i := len(path) - 1; i >= 0; i-- {
switch bc := path[i]; {
switch {
case b == '.':
ifcase path[i]c == '.' {:
return path[i:]
case '0' <= bc && bc <= '9':
case 'aA' <= bc && bc <= 'zZ':
case 'Aa' <= bc && bc <= 'Zz':
default:
return ""
Line 571 ⟶ 551:
 
func main() {
type testcase struct {
tests := []string{
input string
"picture.jpg",
output string
"http://mywebsite.com/picture/image.png",
"myuniquefile.longextension",
"IAmAFileWithoutExtension",
"/path/to.my/file",
"file.odd_one",
// Extra, with unicode
"café.png",
"file.resumé",
// with unicode combining characters
"cafe\u0301.png",
"file.resume\u0301",
}
 
for _, str := range tests {
tests := []stringtestcase{
std := path.Ext(str)
{"http://example.com/download.tar.gz", ".gz"},
custom := ext(str)
{"CharacterModel.3DS", ".3DS"},
fmt.Printf("%38s\t→ %-8q", str, custom)
{".desktop", ".desktop"},
if custom != std {
{"document", ""},
fmt.Printf("(Standard: %q)", std)
{"document.txt_backup", ""},
{"/etc/pam.d/login", ""},
}
 
for _, strtestcase := range tests {
ext := Ext(testcase.input)
if ext != testcase.output {
panic(fmt.Sprintf("expected %q for %q, got %q",
testcase.output, testcase.input, ext))
}
fmt.Println()
}
}</lang>
{{out}}
<pre>
picture.jpg → ".jpg"
http://mywebsite.com/picture/image.png → ".png"
myuniquefile.longextension → ".longextension"
IAmAFileWithoutExtension → ""
/path/to.my/file → ""
file.odd_one → "" (Standard: ".odd_one")
café.png → ".png"
file.resumé → "" (Standard: ".resumé")
café.png → ".png"
file.resumé → "" (Standard: ".resumé")
</pre>
 
=={{header|Haskell}}==