如何从给定的字符串中删除标点符号?

2021年3月24日14:32:03 发表评论 847 次浏览

本文概述

给定字符串, 如果给定字符是按当前C语言环境分类的标点符号, 则从字符串中删除标点符号。默认的C语言环境将这些字符分类为标点符号:

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

例子:

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

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

推荐:请尝试使用{IDE}首先, 在继续解决方案之前。

设计了一个循环, 该循环遍历由该字符串的字符和标点组成的列表, 删除标点, 然后将它们结合在一起。

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

python

# 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

输出如下:

Welcome to lsbin

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: