gpt4 book ai didi

string - 在 go 中迭代 2 个字符串

转载 作者:IT王子 更新时间:2023-10-29 01:59:47 28 4
gpt4 key购买 nike

我想逐个 rune 比较 2 个字符串,看看哪个字符串按任意字母顺序排在第一位。

现在我有这个实现,它在 map[rune]int 中存储一个映射,表示字母在我的字母表中的顺序。

我有这个工作代码。我很清楚当前设计中的缺陷,但这不是问题的重点。

package main

import (
"bufio"
"log"
"math/rand"
"os"
"sort"
)

type Dictionnary struct {
content []string
alphaBeticalOrder map[rune]int
}

func minSize(w1, w2 []rune) int {
if len(w1) < len(w2) {
return len(w1)
}
return len(w2)
}

func (d *Dictionnary) comesFirst(a, b rune) int {

return d.alphaBeticalOrder[a] - d.alphaBeticalOrder[b]
}

func (d Dictionnary) Less(i, j int) bool {
wordi, wordj := []rune(d.content[i]), []rune(d.content[j])
size := minSize(wordi, wordj)
for index := 0; index < size; index++ {
diff := d.comesFirst(wordi[index], wordj[index])
switch {
case diff < 0:
return true
case diff > 0:
return false
default:
continue
}
}
return len(wordi) < len(wordj)
}

func (d Dictionnary) Swap(i, j int) {
d.content[i], d.content[j] = d.content[j], d.content[i]
}

func (d Dictionnary) Len() int {
return len(d.content)
}

func main() {

letters := []rune{'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'}
aOrder := make(map[rune]int)
perm := rand.Perm(len(letters))
for i, v := range perm {
aOrder[letters[i]] = v
}

file, err := os.Open("testdata/corpus.txt")
if err != nil {
log.Fatal(err)
}

corpus := make([]string, 0, 1000)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
corpus = append(corpus, scanner.Text())
}

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

input := Dictionnary{content: corpus, alphaBeticalOrder: aOrder}

sort.Sort(input)

ofile, err := os.Create("testdata/sorted.txt")
writer := bufio.NewWriter(ofile)
for _, v := range input.content {
writer.WriteString(v)
writer.WriteString("\n")
}
writer.Flush()
defer ofile.Close()
}

我的问题涉及 Less(i,j int) bool 函数。是否有更惯用的方法来迭代 2 个字符串以逐个比较它们?我正在此处复制数据,这可能会被避免。

编辑:澄清我的问题是 range(string) 可以让你逐个迭代字符串 rune,但我看不到并排迭代 2 个字符串的方法。我看到的唯一方法是将字符串转换为 []rune。

最佳答案

您可以使用两个词之一的范围使循环稍微更地道。这需要在循环中添加检查,但您不再需要在最终返回时执行检查。

// determines if the word indexed at i is less than the word indexed at j.
func (d Dictionnary) Less(i, j int) bool {
wordi, wordj := []rune(d.content[i]), []rune(d.content[j])
for i, c := range wordi {
if i == len(wordj) {
return false
}

diff := d.comesFirst(c, wordj[i])
switch {
case diff < 0:
return true
case diff > 0:
return false
default:
continue
}
}
return false
}

关于string - 在 go 中迭代 2 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26386346/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com