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
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+6.2k Golang : Use modern ciphers only in secure connection
+3.8k Nginx and PageSpeed build from source CentOS example
+12.1k Facebook PHP getUser() returns 0
+5.1k Golang : Extract XML attribute data with attr field tag example
+34k Golang : How to split or chunking a file to smaller pieces?
+22.8k Golang : Daemonizing a simple web server process example
+11.7k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+7.3k Swift : Convert (cast) Character to Integer?
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+12.1k Swift : Convert (cast) Int to String ?
+10.8k Golang : Save webcamera frames to video file