Remove Punctuation from a String in Go



In this tutorial, we will learn how to remove punctuation from a string in Go. We will cover the basic concept of string manipulation and implement a function to perform the operation.


What is String Manipulation

String manipulation involves altering, parsing, and analyzing strings in various ways. Removing punctuation from a string is a common task in text processing and data cleaning.


Syntax

The syntax to remove punctuation from a string in Go is:

import (
    "fmt"
    "strings"
    "unicode"
)

func removePunctuation(s string) string {
    var result strings.Builder
    for _, char := range s {
        if !unicode.IsPunct(char) {
            result.WriteRune(char)
        }
    }
    return result.String()
}


Example 1: Removing punctuation from a string

We can create a function to remove punctuation from a given string by iterating through its characters and appending non-punctuation characters to a result string.

For example,

  1. Import the fmt, strings, and unicode packages.
  2. Define a function named removePunctuation that takes one parameter s of type string.
  3. Initialize a strings.Builder to build the result string.
  4. Use a for loop to iterate through the characters of the input string.
  5. In each iteration, check if the character is not a punctuation mark using unicode.IsPunct. If true, append the character to the result string.
  6. Return the result string.
  7. In the main function, call the removePunctuation function with a sample string and print the result.

Go Program

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func removePunctuation(s string) string {
    var result strings.Builder
    for _, char := range s {
        if !unicode.IsPunct(char) {
            result.WriteRune(char)
        }
    }
    return result.String()
}

func main() {
    // Sample string
    sampleString := "Hello, world! Welcome to Go programming."

    // Remove punctuation from the sample string
    result := removePunctuation(sampleString)

    // Print the result
    fmt.Println("String without punctuation:", result)
}

Output

String without punctuation: Hello world Welcome to Go programming