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
+11.7k Python : Convert IPv6 address to decimal and back to IPv6
+5.4k Golang : Convert an executable file into []byte example
+28.1k Golang : Get time.Duration in year, month, week or day
+24.6k Golang : Get executable name behind process ID example
+10.5k Golang : Change date format to yyyy-mm-dd
+10.8k Golang : Simple client-server HMAC authentication without SSL example
+10k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+7.7k Golang : Find network service name from given port and protocol
+7.9k Golang : Find the length of big.Int variable example
+38.1k Golang : UDP client server read write example
+4k Golang : Print instead of building pyramids
+16.4k Golang : Upload/Receive file progress indicator