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
+7.3k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+22.6k Golang : Convert Unix timestamp to UTC timestamp
+23.1k Golang : Calculate time different
+15.4k Golang : Save(pipe) HTTP response into a file
+20.1k Golang : Measure http.Get() execution time
+10.8k Golang : Get local time and equivalent time in different time zone
+9.9k Golang : Load ASN1 encoded DSA public key PEM file example
+8.3k Golang : How To Use Panic and Recover
+6.8k Golang : Warp text string by number of characters or runes example
+8.5k Golang : Convert word to its plural form example
+17.2k Golang : Get number of CPU cores
+12.5k Golang : Display list of countries and ISO codes