fork download
  1. package main
  2.  
  3. import (
  4. "os"
  5. "io/ioutil"
  6. "fmt"
  7. "strings"
  8. )
  9.  
  10. func main() {
  11. file := os.Args[1]
  12. word := os.Args[2]
  13.  
  14. buffer, err := ioutil.ReadFile(file)
  15.  
  16. if( err != nil ) {
  17. fmt.Println("failed to read: ", file)
  18. return
  19. }
  20.  
  21. content := string(buffer)
  22. fmt.Println( search1(word,content) )
  23. fmt.Println( search2(word,content) )
  24. fmt.Println( search3(word,content) )
  25. }
  26.  
  27.  
  28. func search1( word string, content string ) bool {
  29. return strings.Index(content,word) != (-1)
  30. }
  31.  
  32. func search2( word string, content string ) int {
  33. return strings.Count(content,word);
  34. }
  35.  
  36. type Pos struct {
  37. a int
  38. b int
  39. }
  40. type Search3Result struct {
  41. bool
  42. int
  43. pos []Pos
  44. }
  45.  
  46. func search3( word string, content string ) Search3Result {
  47. indices := []Pos{}
  48.  
  49. for l, line := range strings.Split(content,"\n") {
  50. for i := 0;; i++ {
  51. n := strings.Index(line[i:],word)
  52. if( n == (-1) ){ break; }
  53. i += n
  54. indices = append(indices, Pos{l,i})
  55. }
  56. }
  57.  
  58. return Search3Result{ len(indices) > 0, len(indices), indices }
  59. }
  60.  
  61.  
Runtime error #stdin #stdout #stderr 0s 3152KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x4a5140, 0xc42000a090)
	/usr/lib/go-1.7/src/runtime/panic.go:500 +0x1a1
main.main()
	/home/4leAaj/prog.go:11 +0x435