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
+15.6k Golang : Generate universally unique identifier(UUID) example
+7.7k Findstr command the Grep equivalent for Windows
+8.9k Golang : How to control fmt or log print format?
+5.5k Golang : Find change in a combination of coins example
+5.6k nginx : force all pages to be SSL
+7.6k Golang : Grayscale Image
+16.7k Golang : How to save log messages to file?
+5k Javascript : How to loop over and parse JSON data?
+26.3k Golang : How to check if a connection to database is still alive ?
+40.5k Golang : How to check if a string contains another sub-string?
+4.7k Golang : Check if a word is countable or not
+19.6k Golang : Check if os.Stdin input data is piped or from terminal