Golang : Get all upper case or lower case characters from string example
Problem:
You have a string and you want to get all the uppercase characters in the string. For example, you want to get the characters of A,O and H from the string "Ace Of Hearts" and use the AOH
to make a key for your string map. How to do that?
Solution:
Use unicode.IsLower()
function to determine if the character is lowercase or not. If not, then push the characters into a slice or form a string with strings.Join()
function.
Here you go!
package main
import (
"fmt"
"regexp"
"strings"
"text/scanner"
"unicode"
)
// faster way to get rid delimiters
// for string without unicode
func removeDelimString(str string) string {
// alphanumeric (== [0-9A-Za-z])
// \s is a white space character
regExp := regexp.MustCompile(`[^[:alnum:]\s]`)
return regExp.ReplaceAllString(str, "")
}
// get all upper case characters from string
// to get all lower case characters, just remove the exclamation mark !
// infront of unicode.IsLower()
func getUpperCaseChars(str string) []string {
tokens := removeDelimString(str)
var result []string
for _, char := range tokens {
if !unicode.IsLower(char) && char != ' ' {
fmt.Println(scanner.TokenString(char))
result = append(result, scanner.TokenString(char))
}
}
return result
}
func main() {
str := "This a string with some UpperCase Characters."
temp := getUpperCaseChars(str)
for k, v := range temp {
fmt.Println(k, v)
}
// form into a UPPERCASE string
upper := removeDelimString(strings.Join(temp, ""))
fmt.Println(upper)
}
Output:
"T"
"U"
"C"
"C"
0 "T"
1 "U"
2 "C"
3 "C"
TUCC
References:
https://www.socketloop.com/tutorials/golang-how-to-join-strings
https://golang.org/pkg/unicode/#IsLower
https://socketloop.com/tutorials/golang-break-string-into-a-slice-of-characters-example
See also : Golang : Break string into a slice of characters example
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
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+10.2k Swift : Convert (cast) String to Integer
+19.9k Golang : Count number of digits from given integer value
+15.3k Golang : Validate hostname
+7.4k Gogland : Where to put source code files in package directory for rookie
+9k Golang : Generate random Chinese, Japanese, Korean and other runes
+6k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+11.4k CodeIgniter : Import Linkedin data
+5.1k Golang : Return multiple values from function
+20.9k Golang : Create and resolve(read) symbolic links
+3.9k Javascript : Empty an array example
+4.5k Linux/MacOSX : How to symlink a file?