I am a java developer and I am trying to learn Go.
I tried to make a simple code that take numbers from a .txt
file and make print them in a prettier format.
That is:
0613228745 -> 06 13 22 87 45
06.13.22.87.45 -> 06 13 22 87 45
06-13-22-87-45 -> 06 13 22 87 45
06 13 228 745 -> 06 13 22 87 45
0 613 228 745 -> 06 13 22 87 45
Can you review, give me some advices about my code ? Here it is:
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
file, err := os.Open("./phonenumbers.txt")
check(err)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
basicPhoneNumberArray, prettyPhoneNumber := make([]rune, 0), ""
// get only digit numbers
for _, r := range []rune(scanner.Text()) {
if unicode.IsDigit(r) {
basicPhoneNumberArray = append(basicPhoneNumberArray, r)
}
}
// put spaces every two digits
for i, r := range basicPhoneNumberArray {
prettyPhoneNumber += string(r)
if i%2 != 0 && i != len(basicPhoneNumberArray)-1 { // no space at the end
prettyPhoneNumber += " "
}
}
fmt.Println(prettyPhoneNumber)
}
}
Also I am very fond of functional programming, I think there should be a way to use some filter
and map
here but after few searches I didn't find a way. If you could give me some advices about that too that would be great :D.