获取循环子字符串的最佳方法是什么?

huangapple go评论85阅读模式
英文:

What is the best way to get cyclic substrings

问题

我想要类似这样的结果:

var peptide = "LENQ"

peptide[2:3] -> NQ
peptide[2:4] -> NQL
peptide[2:5] -> NQLE

在Go语言中,有没有现成的库函数可以实现这个功能?或者我需要自己编写代码来实现呢?

英文:

I want something like:

var peptide = "LENQ"

peptide[2:3] -> NQ
peptide[2:4] -> NQL
peptide[2:5] -> NQLE

What is the best way in go to do it? May be there is a library function to get it or do I need to write it by myself ?

答案1

得分: 4

例如,

package main

import (
	"fmt"
	"unicode/utf8"
)

func cyclicSubstrings(str string) []string {
	n := utf8.RuneCountInString(str)
	substrs := make([]string, 0, n*n)
	cycles := str + str
	for i := range str {
		cycle := cycles[i : i+len(str)]
		for j, r := range cycle {
			substrs = append(substrs, cycle[:j+utf8.RuneLen(r)])
		}
	}
	return substrs
}

func main() {
	peptide := "LENQ"
	fmt.Println(cyclicSubstrings(peptide))
}

输出:

[L LE LEN LENQ E EN ENQ ENQL N NQ NQL NQLE Q QL QLE QLEN]
英文:

For example,

package main

import (
	"fmt"
	"unicode/utf8"
)

func cyclicSubstrings(str string) []string {
	n := utf8.RuneCountInString(str)
	substrs := make([]string, 0, n*n)
	cycles := str + str
	for i := range str {
		cycle := cycles[i : i+len(str)]
		for j, r := range cycle {
			substrs = append(substrs, cycle[:j+utf8.RuneLen(r)])
		}
	}
	return substrs
}

func main() {
	peptide := "LENQ"
	fmt.Println(cyclicSubstrings(peptide))
}

Output:

<pre>
[L LE LEN LENQ E EN ENQ ENQL N NQ NQL NQLE Q QL QLE QLEN]
</pre>

huangapple
  • 本文由 发表于 2014年11月8日 22:48:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/26818299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定