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
+18k Golang : How to remove certain lines from a file
+27.6k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+7.2k Golang : Individual and total number of words counter example
+9.9k Golang : Get login name from environment and prompt for password
+4.8k Linux : How to set root password in Linux Mint
+13.5k Golang : How to determine if a year is leap year?
+8.5k Golang : On lambda, anonymous, inline functions and function literals
+11.5k Golang : How to detect a server/machine network interface capabilities?
+4.4k JavaScript : Rounding number to decimal formats to display currency
+11.8k Golang : Decompress zlib file example
+13.2k Golang : Read from buffered reader until specific number of bytes
+9.7k Golang : Convert octal value to string to deal with leading zero problem