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

本文概述

  • 建议:在继续解决方案之前, 请先在{IDE}上尝试使用你的方法。
  • C ++
  • Java
  • python
  • C#
给定字符串, 如果给定字符是按当前C语言环境分类的标点符号, 则从字符串中删除标点符号。默认的C语言环境将这些字符分类为标点符号:
!"#$%& '()*+, -./:; ?@[\]^_`{|}~

例子:
Input : %welcome' to @geeksforgeek< sOutput : welcome to lsbinInput : 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 stringpublic 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

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

    推荐阅读