How to check if a character is a punctuation mark in C#

The Char.IsPunctuation() method is a C# character method that is used to check if a character is categorized as a punctuation mark.

Syntax

// for a single character
IsPunctuation(Char)
// for a character in a string
IsPunctuation(String, Int32)

Parameters

  • Char: The character we want to check.

  • String: A string we want to check to see if its character specified at an index position is punctuation.

  • Int32: The index position of a character in a string that we want to check to see if it is a punctuation mark or not.

Return value

Char.isPunctuation returns a boolean value of true if the character is punctuation; else, it returns false.

Code example

We will demonstrate the use of the IsPunctuation() method in the example below.

// use System
using System;
// create class
class PunctuationChecker
{
// create method
static void Main()
{
// create characters
char c1 = '?';
char c2 = '.';
char c3 = ';';
char c4 = 't';
// create some strings
string s1 = "Hello!";
string s2 = "Edpresso";
// check if characters are
// punctuation marks
bool a = Char.IsPunctuation(c1);
bool b = Char.IsPunctuation(c2);
bool c = Char.IsPunctuation(c3);
bool d = Char.IsPunctuation(c4);
bool e = Char.IsPunctuation(s1, 5); // last position
bool f = Char.IsPunctuation(s2, 2); // third position
// print out returned values
Console.WriteLine(a); // True
Console.WriteLine(b); // True
Console.WriteLine(c); // True
Console.WriteLine(d); // False
Console.WriteLine(e); // True
Console.WriteLine(f); // False
}
}

As seen in the code above, every specified character is a punctuation mark except c4, which is 't', and the third character in string s2, which is 'r'.