2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go言語によるWebアプリケーション開発 4.2.1.1 練習問題

Posted at

変換方法のカスタマイズ

配列transformsの内容をハードコードするのではなく、テキストファイルやデータベースなどから読み込んでカスタマイズできるようにしてみましょう。

準備

  • 同じディレクトリ位置にword.txtを用意しておく
word.txt
get*
go*
lets*
*web
*ty
*ing
*done
we*
my*
you*
main.go
package main
import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strings"
	"time"
	"errors"
)
const otherWord = "*"
var ErrFileNotFound = errors.New("ファイルが見つかりませんでした")

func makeWords() ([]string) {
	var transforms = []string{
		otherWord,
		otherWord,
		otherWord,
		otherWord,
		otherWord + "app",
		otherWord + "site",
		otherWord + "time",
		"get" + otherWord,
		"go" + otherWord,
		"lets" + otherWord,
	}
	return transforms
}

func makeWords_FromFile() ([]string, error) {
	file, err := os.Open("word.txt")
	var transforms = []string{}
	if err != nil {
		fmt.Println("word.txt not found!")
		return nil, ErrFileNotFound
	}else{
		var words = bufio.NewScanner(file)
		for words.Scan() {
			transforms = append(transforms, words.Text())
		}
	}
	return transforms, nil
}

func main(){
	transforms, err := makeWords_FromFile()
	if err != nil {
		transforms = makeWords()
	}
	rand.Seed(time.Now().UTC().UnixNano())
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		t := transforms[rand.Intn(len(transforms))]
		fmt.Println(strings.Replace(t, otherWord, s.Text(), -1))
	}
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?