Home > Back-end >  How to read a word in upper and lower case from file? Go
How to read a word in upper and lower case from file? Go

Time:07-18

I have a task to read a file and, then scan for "bad word", and finally output "True" or "False" if "bad word" contains in file or not. I wrote this function:

func readFile(fileName string, tabooName string) {
    dataFile, err := os.Open(fileName)
    if err != nil {
        log.Fatal(err)
    }
    defer dataFile.Close()

    scanner := bufio.NewScanner(dataFile)

    for scanner.Scan() {
        scanner.Text()
        if strings.Contains(scanner.Text(), strings.ToLower(tabooName)) || strings.Contains(scanner.Text(), strings.ToUpper(tabooName)) {
            fmt.Println("True")
            break
        } else {
            fmt.Println("False")
            break
        }
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

But it does not work if the "bad word" is written in UPPERCASE For example:

Wrong answer in test #2

This word belongs to bad words

Please find below the output of your program during this failed test.
Note that the '>' character indicates the beginning of the input line.

---

forbidden_words.txt
HARSH
False

How can i do it corectly?

UPDATE: I don't know why but this function is working now... First, i justed wrote this whole func in main function, and it's working, now with func it's working too. I don't know why lol

CodePudding user response:

You could use strings.Contains and strings.ToLower slightly differently:

func readFile(fileName string, tabooName string) {
    file, err := os.Open(fileName)
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    tabooNameLowered := strings.ToLower(tabooName)

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        loweredLine := strings.ToLower(scanner.Text())
        if strings.Contains(loweredLine, tabooNameLowered) {
            fmt.Println("True")
            return
        }
    }
        
    fmt.Println("False")

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}
  • Related