Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

substr doesn't respects runes (utf8 characters) #351

Open
Klaus-Tockloth opened this issue Nov 12, 2022 · 0 comments
Open

substr doesn't respects runes (utf8 characters) #351

Klaus-Tockloth opened this issue Nov 12, 2022 · 0 comments

Comments

@Klaus-Tockloth
Copy link

The current substr (substring) implementation does not respect runes (utf8 characters).

func main() {
	hello := "馃槥-Hello World-馃槥"
	fmt.Printf("substring = %s\n", substring(0, 5, hello))
	fmt.Printf("substringRune = %s\n", substringRune(0, 5, hello))
	fmt.Printf("substring = %s\n", substring(2, 7, hello))
	fmt.Printf("substringRune = %s\n", substringRune(2, 7, hello))
}

func substringRune(start, end int, s string) string {
	if start < 0 {
		return string([]rune(s)[:end])
	}
	if end < 0 || end > len(s) {
		return string([]rune(s)[start:])
	}
	return string([]rune(s)[start:end])
}

func substring(start, end int, s string) string {
	if start < 0 {
		return s[:end]
	}
	if end < 0 || end > len(s) {
		return s[start:]
	}
	return s[start:end]
}

Output
substring = 馃槥-
substringRune = 馃槥-Hel
substring = ??-He
substringRune = Hello

Remarks
substring(): current implementation
substringRune(): implementation that also works with runes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant