mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 14:42:01 +00:00
good good study, day day up!
This commit is contained in:
44
vendor/gopl.io/ch3/basename1/main.go
generated
vendored
Normal file
44
vendor/gopl.io/ch3/basename1/main.go
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 72.
|
||||
|
||||
// Basename1 reads file names from stdin and prints the base name of each one.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
input := bufio.NewScanner(os.Stdin)
|
||||
for input.Scan() {
|
||||
fmt.Println(basename(input.Text()))
|
||||
}
|
||||
// NOTE: ignoring potential errors from input.Err()
|
||||
}
|
||||
|
||||
//!+
|
||||
// basename removes directory components and a .suffix.
|
||||
// e.g., a => a, a.go => a, a/b/c.go => c, a/b.c.go => b.c
|
||||
func basename(s string) string {
|
||||
// Discard last '/' and everything before.
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
if s[i] == '/' {
|
||||
s = s[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
// Preserve everything before last '.'.
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
if s[i] == '.' {
|
||||
s = s[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
//!-
|
Reference in New Issue
Block a user