Golang : How to detect if a sentence ends with a punctuation?
Problem : I need to detect if a line ends with a punctuation mark or not. How to do that?
Solution : In Golang, a string is also a slice, get the last character out from the sentence, convert the string to rune and use unicode.IsPunct()
function to check if the last character is a punctuation or not.
Here you go!
package main
import (
"log"
"unicode"
)
func main() {
//str := "this is a line with fullstop."
str := "this is a line with without fullstop"
lastChar := str[len(str)-1:]
lastCharRune := []rune(lastChar)
if unicode.IsPunct(lastCharRune[0]) { // this is how to convert string to rune ;-)
log.Println("lastChar is a punctuation :", lastChar)
} else {
log.Println("lastChar is not a punctuation :", lastChar)
}
}
Happy coding!
See also : Golang : Use NLP to get sentences for each paragraph 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
+18.8k Golang : Delete item from slice based on index/key position
+9.8k Golang : cannot assign type int to value (type uint8) in range error
+9.8k Golang : How to get quoted string into another string?
+10.1k Golang : Resolve domain name to IP4 and IP6 addresses.
+16.9k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+8.2k Golang : Set or add headers for many or different handlers
+5.2k PHP : Fix Call to undefined function curl_init() error
+13.3k Golang : Check if an integer is negative or positive
+11.5k Golang : Sort and reverse sort a slice of runes
+8.9k Golang : Find the length of big.Int variable example
+7.1k Golang : Rot13 and Rot5 algorithms example
+9.6k Golang : Setting variable value with ldflags