C# char type
Description
C#'s char type represents a Unicode character and occupies two bytes. Aliasing the System.Char type.
Literial
A char literal is specified inside single quotes:
char c = 'A'; // Simple character
The following code stores character a to char type variable:
using System;/* w w w.j av a 2s .co m*/
class Program
{
static void Main(string[] args)
{
char ch = 'a';
Console.WriteLine(ch);
}
}
The output:
Escape sequences
Escape sequences express characters that cannot be expressed literally.
An escape sequence is a backslash followed by a character with a special meaning. For example:
char newLine = '\n';
char backSlash = '\\';
The escape sequence characters are shown in the following table.
Char | Meaning | Value |
---|---|---|
\' | Single quote | 0x0027 |
\" | Double quote | 0x0022 |
\\ | Backslash | 0x005C |
\0 | Null | 0x0000 |
\a | Alert | 0x0007 |
\b | Backspace | 0x0008 |
\f | Form feed | 0x000C |
\n | New line | 0x000A |
\r | Carriage return | 0x000D |
\t | Horizontal tab | 0x0009 |
\v | Vertical tab | 0x000B |
The \u (or \x) escape sequence lets you specify any Unicode character via its fourdigit hexadecimal code:
The following code shoes how to create unicode char literal:
using System;/*from ww w .jav a 2 s . c o m*/
class Program
{
static void Main(string[] args)
{
char copyrightSymbol = '\u00A9';
char aSymbol = '\u03A9';
Console.WriteLine(copyrightSymbol);
Console.WriteLine(aSymbol);
}
}
The code above generates the following result.
Char Conversions
An implicit conversion from a char to a numeric type works for the numeric types that can accommodate an unsigned short.
For other numeric types, an explicit conversion is required.
Example
The following code shows some of the basic methods from Char structure.
using System;// w ww . j a va 2s. co m
public class Test{
public static void Main() {
char chA = 'A';
char ch1 = '1';
string str = "java2s.com";
Console.WriteLine(chA.CompareTo('B'));
Console.WriteLine(chA.Equals('A'));
Console.WriteLine(Char.GetNumericValue(ch1));
Console.WriteLine(Char.IsControl('\t'));
Console.WriteLine(Char.IsDigit(ch1));
Console.WriteLine(Char.IsLetter(','));
Console.WriteLine(Char.IsLower('u'));
Console.WriteLine(Char.IsNumber(ch1));
Console.WriteLine(Char.IsPunctuation('.'));
Console.WriteLine(Char.IsSeparator(str, 4));
Console.WriteLine(Char.IsSymbol('+'));
Console.WriteLine(Char.IsWhiteSpace(str, 4));
Console.WriteLine(Char.Parse("S"));
Console.WriteLine(Char.ToLower('M'));
Console.WriteLine('x'.ToString());
}
}
The output: