The Wayback Machine - https://web.archive.org/web/20240623194043/https://www.geeksforgeeks.org/removing-punctuations-given-string/
Open In App

Removing punctuations from a given string

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, remove the punctuation from the string if the given character is a punctuation character, as classified by the current C locale. The default C locale classifies these characters as punctuation: 

! " # $ % & ' ( ) * + , - . / : ; ? @ [ \ ] ^ _ ` { | } ~ 

Examples: 

Input : %welcome' to @geeksforgeek<s
Output : welcome to geeksforgeeks

Input : Hello!!!, he said ---and went.
Output : Hello he said and went

Approach: First check the input string if it consists of punctuations then we have to make it punctuation free. In order to do this, we will traverse over the string, and if punctuations are found we will remove them. Let’s say the input string is ‘$Student@‘ then we have to remove $ and @, furthermore we have to print the plain string ‘Student‘ which is free from any punctuations.

Algorithm:

  1. Initialize the input string
  2. Check if the character present in the string is punctuation or not.
  3. If a character is a punctuation, then erase that character and decrement the index.
  4. Print the output string, which will be free of any punctuation.

Below is the implementation of the above approach:

C++




// CPP program to remove punctuation from a given string
 
#include <iostream>
using namespace std;
 
int main()
{
    // input string
    std::string str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
 
    for (int i = 0, len = str.size(); i < len; i++)
    {
        // check whether parsing character is punctuation or not
        if (ispunct(str[i]))
        {
            str.erase(i--, 1);
            len = str.size();
        }
    }
     
    // print string without punctuation
    std::cout << str;
    return 0;
}


Java




// Java program to remove punctuation from a given string
 
public class Test
{
    public static void main(String[] args)
    {
        // input string
        String str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
         
        // similar to Matcher.replaceAll
        str = str.replaceAll("\\p{Punct}","");
         
        System.out.println(str);
    }
     
}
// This code is contributed by Gaurav Miglani


Python3




# Python program to remove punctuation from a given string
# Function to remove punctuation
def Punctuation(string):
 
    # punctuation marks
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
 
    # traverse the given string and if any punctuation
    # marks occur replace it with null
    for x in string.lower():
        if x in punctuations:
            string = string.replace(x, "")
 
    # Print string without punctuation
    print(string)
 
# Driver program
string = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;"
Punctuation(string)


C#




// C# program to remove punctuation
// from a given string
using System;
using System.Text.RegularExpressions;                
 
class GFG
{
public static void Main()
{
    // input string
    String str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
     
    // similar to Matcher.replaceAll
    str = Regex.Replace(str,@"[^\w\d\s]","");
     
    Console.Write(str);
}
}
 
// This code is contributed
// by 29AjayKumar


Javascript




<script>
 
// JavaScript program to remove punctuation from a given string
    {
        // input string
        var str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
         
        // similar to Matcher.replaceAll
        str = str.replace(/[^a-zA-Z ]/g, "");
         
        document.write(str);
    }
     
// This code is contributed by shivanisingh
 
</script>


Output

Welcome to GeeksforGeeks

Time Complexity: O(n2) 
Auxiliary Space: O(1)

Approach 2 : –  Using a loop to iterate over the string and remove punctuations

   Initialize an empty string called result.
   Iterate over the characters in the given string using a loop.
   For each character, check if it is a punctuation character using the ispunct function.
   If the character is not a punctuation character, add it to the result string.
   Repeat steps 3-4 for all characters in the string.
   Replace the original string with the result string, effectively removing all punctuation characters from the original string.

This approach may be useful in cases where you need to perform additional operations on each character in the string before removing punctuations, or if you need to process the string character-by-character rather than using a built-in algorithm.

C++




// CPP program to remove punctuation from a given string
 
#include <iostream>
using namespace std;
string removePunctuations(std::string& s) {
    std::string result = "";
    for (char c : s) {
        if (!ispunct(c)) { // If c is not a punctuation character
            result += c;
        }
    }
    s = result;
    return s;
}
 
int main()
{
    // input string
    std::string str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
 
    // print string without punctuation
    std::cout << removePunctuations(str);
    return 0;
}


Java




//GFG
//Java Code for the given approach
import java.util.*;
public class RemovePunctuations {
    public static String removePunctuations(String s) {
        StringBuilder result = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) { // If c is a letter, digit, or whitespace
                result.append(c);
            }
        }
        return result.toString();
    }
     
    public static void main(String[] args) {
        // input string
        String str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
 
        // print string without punctuation
        System.out.println(removePunctuations(str));
    }
}
// This code is written by Sundaram


Python3




import re
 
# Function to remove punctuation from a given string
def removePunctuations(s):
    result = ""
    for c in s:
        if not re.match(r"[.,\/#!$%\^&\*;:{}=\-_`~()@?]", c): # If c is not a punctuation character
            result += c
    s = result
    return s
 
# Main function
# Input string
str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;"
 
# Print string without punctuation
print(removePunctuations(str))


C#




using System;
using System.Text.RegularExpressions;
 
class Program {
    static void Main(string[] args)
    {
        // Input string
        string str
            = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
 
        // Print string without punctuation
        Console.WriteLine(RemovePunctuations(str));
    }
 
    // Function to remove punctuation from a given string
    static string RemovePunctuations(string s)
    {
        string result = "";
        foreach(char c in s)
        {
            if (!Regex.IsMatch(
                    c.ToString(),
                    @"[.,\/#!$%\^&\*;:{}=\-_`~()@?]")) // If
                                                       // c
                                                       // is
                                                       // not
                                                       // a
                                                       // punctuation
                                                       // character
            {
                result += c;
            }
        }
        s = result;
        return s;
    }
}


Javascript




// Function to remove punctuation from a given string
function removePunctuations(s) {
    let result = "";
    for (let c of s) {
        if (!c.match(/[.,\/#!$%\^&\*;:{}=\-_`~()@?]/g)) { // If c is not a punctuation character
            result += c;
        }
    }
    s = result;
    return s;
}
 
// Main function
// Input string
let str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks;";
 
// Print string without punctuation
console.log(removePunctuations(str));


Output

Welcome to GeeksforGeeks

Time Complexity: O(n), where n is the size of the string
Auxiliary Space: O(1)

 



Similar Reads

Return a Palindromic String after removing minimum length Prefix from given String
Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanation: We can remove the prefix "a" from the string "a
5 min read
Print string after removing all (“10” or “01”) from the binary string
Given a binary string str consisting of only 0's and 1's, the task is to print the string after removing the occurrences of "10" and "01" from the string one by one. Print -1 if the string becomes null. Examples: Input: str = "101100" Output: -1 Explanation: In the first step, "10" at index 0 and 1 is removed from the string. 101100 -&gt; 1100 In t
9 min read
Smallest string obtained by removing all occurrences of 01 and 11 from Binary String
Given a binary string S , the task is to find the smallest string possible by removing all occurrences of substrings "01" and "11". After removal of any substring, concatenate the remaining parts of the string. Examples: Input: S = "0010110"Output:Length = 1 String = 0Explanation: String can be transformed by the following steps: 0010110 ? 00110 ?
7 min read
Minimize a string by removing all occurrences of another string
Given two strings S1 and S2 of length N and M respectively, consisting of lowercase letters, the task is to find the minimum length to which S1 can be reduced by removing all occurrences of the string S2 from the string S1. Examples: Input: S1 ="fffoxoxoxfxo", S2 = "fox";Output: 3Explanation:By removing "fox" starting from index 2, the string modif
7 min read
Minimize length of a string by removing occurrences of another string from it as a substring
Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S[3]} and modifies the remaining string to "abcbd".
8 min read
Smallest string obtained by removing all occurrences of 01 and 11 from Binary String | Set 2
Given a binary string S of length N, the task is to find the smallest string possible by removing all occurrences of substrings “01” and “11”. After removal of any substring, concatenate the remaining parts of the string. Examples: Input: S = "1010"Output: 2Explanation: Removal of substring "01" modifies string S to "10". Input: S = "111"Output: 1
5 min read
Removing string that is an anagram of an earlier string
Given an array arr of strings, the task is to remove the strings that are an anagram of an earlier string, then print the remaining array in sorted order. Examples: Input: arr[] = { "geeks", "keegs", "code", "doce" }, N = 4 Output: ["code", "geeks"] Explanation: "geeks" and "keegs" are anagrams, so we remove "keegs". Similarly, "code" and "doce" ar
7 min read
Check if string remains palindrome after removing given number of characters
Given a palindromic string str and an integer N. The task is to find if it is possible to remove exactly N characters from the given string such that the string remains a palindrome. Examples: Input: str = "abba", N = 1 Output: Yes Remove 'b' and the remaining string "aba" is still a palindrome. Input: str = "aba", N = 1 Output: Yes Approach: It ca
3 min read
Minimize cost to empty a given string by removing characters alphabetically
Given string str, the task is to minimize the total cost to remove all the characters from the string in alphabetical order. The cost of removing any character at i th index from the string will be i. The indexing is 1-based. Examples: Input: str = "abcab" Output: 8 Explanation: First char ‘a’ at index 1 is removed, str[] becomes “bcab”, Then char
7 min read
Check if permutation of a given string can be made palindromic by removing at most K characters
Given a string str and an integer K, the task is to check if a permutation of the given string can be made a palindromic by removing at most K characters from the given string. Examples: Input: str = "geeksforgeeks", K = 2 Output: Yes Explanation: Removing (str[5], str[6]) from the given string makes the remaining string "geeksrgeeks" palindromic.
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg