Golang : Test input string for unicode example
Problem:
You are trying to create a slightly different solution for user that use unicode and you want to test if an input string has unicode characters within? How to do that?
Solution:
Measure the input string twice. Once with len()
function and another with utf8.RuneCountInString()
function. If both length is the same, then there is no unicode detected within the input string.
Here you go!
package main
import (
"bufio"
"fmt"
"os"
"strings"
"unicode/utf8"
)
// test to see if the input string has unicode
func testStringForUnicode(s string) bool {
a := len(s)
b := utf8.RuneCountInString(s)
if a == b {
return false
} else {
return true
}
}
func main() {
fmt.Println("Enter a word, phrase or number : ")
consoleReader := bufio.NewReader(os.Stdin)
answer, _ := consoleReader.ReadString('\n')
// get rid of the extra newline character from ReadString() function
answer = strings.TrimSuffix(answer, "\n")
fmt.Println(answer, " have unicode characters ? ", testStringForUnicode(answer))
}
Sample output:
Enter a string with or without unicode :
fuß is german language for foot
fuß is german language for foot have unicode characters ? true
Enter a string with or without unicode :
foot is english language for foot
foot is english language for foot have unicode characters ? false
See also : Golang : Handle Palindrome string with case sensitivity and unicode
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+29k Golang : Save map/struct to JSON or XML file
+6.3k Golang : How to determine if request or crawl is from Google robots
+13.6k Golang : How to check if a file is hidden?
+33.6k Golang : Proper way to set function argument default value
+21.7k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+12k Golang : How to display image file or expose CSS, JS files from localhost?
+8.5k Golang : Heap sort example
+20.4k PHP : Convert(cast) int to double/float
+11.9k Golang : Simple client-server HMAC authentication without SSL example
+6.3k Elasticsearch : Shutdown a local node
+6.2k Grep : How to grep for strings inside binary data
+17.7k Golang : How to log each HTTP request to your web server?