How to check if a character is a separator in C#

Overview

In C#, we use the IsSeparator() character method to check if a specified character is categorized as a separator.

Even in a string, we can check if a character is a separator by passing the index position of the character in the string to the IsSeparator() method.

A separator can be a space separator, line separator, or paragraph separator.

Syntax

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

Parameters

Char: The character to check.

String: This string contains a character we want to check.

Int32: The index position of a character in a string that we want to check.

Return value

This method returns a Boolean value. It returns true if the character specified is a separator. Otherwise, it returns false.

Code example

In the example below, we’ll look at how to use the IsSeparator() method on characters and strings. We’ll also check whether the specified characters are separators or not.

// using System
using System;
// create class
class SeparatorChecker
{
// main method
static void Main()
{
// create characters
char c1 = ' ';
char c2 = '\u0020';
// create strings
string s1 = "hello world";
string s2 = "c#";
// check for separators
bool a = Char.IsSeparator(c1);
bool b = Char.IsSeparator(c2);
bool c = Char.IsSeparator(s1, 5); // 6th position
bool d = Char.IsSeparator(s2, 1); // 2nd position
// return values
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
}
}

From the code above, all characters specified are separators, except the string s2 character at index position 1, which is #. Hence, they all return true, except for s2.

Free Resources