-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
46 lines (43 loc) · 1.13 KB
/
Copy pathmain.go
File metadata and controls
46 lines (43 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// main.go
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
)
func main() {
word:=flag.String("word","","we will try to give you the count it appeared")
flag.Parse()
path,err:=os.Getwd()
file,err:=os.Open(path+"/data.txt")//readfile loads whole thing in memory
if err!=nil{
log.Fatal(err)//terminates prgm after showeing err
}
defer file.Close()
scanner := bufio.NewScanner(file)
count:=0
searchword:=strings.ToLower(*word)
start:=time.Now()
for scanner.Scan() {
text := scanner.Text()
//btext:=[]byte(text)
// for i:=0;i<len(btext);i++{
// // if(strings.Contains(string(btext[i]),*word)){
// // count++
// // }
// }
//bufio.scanner gives full line of text , strings is capable of reading full line directly
text=strings.ToLower(text)
count+=(strings.Count(text,searchword))
}
if err:=scanner.Err();err!=nil{//if error ocurs in scanner.scan it will already exit loop with the limited date it got so after finishing loop we r taking log
log.Fatal(err)
}
fmt.Println(*word,"appeared ",count,"times in data.txt")
elapsed:=time.Since(start)
fmt.Println("elapsed time: ",elapsed)
}