接上一篇.net框架读书笔记---属性、索引器,接下来继续开始学习.net框架中的文本处理。
一、字符
在.NET中,字符采用16位Unicode编码,一个字符有一个System.Char结构(值类型)表示。它提供两个常数字段:MinValue(定义为0x0000)和MaxValue(定义为0xFFFF)。
给定一个char实例作为参数,我们可以调用char的静态方法GetUnicodeCategory返回一个System.Globalization.UnicodeCategory枚举值,可以根据该枚举值来判断字符的类型(是否是数字。是否是标点符号。。。。。。。。。)
namespace CharStudy
{
class Program
{
static void Main( string [] args)
{
Console.WriteLine( char .GetUnicodeCategory( ' c ' ));
Console.WriteLine( char .GetUnicodeCategory( ' 4 ' ));
Console.WriteLine( char .GetUnicodeCategory( ' , ' ));
Console.WriteLine( char .GetUnicodeCategory( ' A ' ));
Console.WriteLine( char .GetUnicodeCategory( ' $ ' ));
}
}
}
上面代码的输出值为
char有一些静态方法,专门用于判断字符的类型,eg.IsDigit,IsLetter,IsUpper,IsLower.........这些方法在内部实现的时候都调用了GetUnicodeCategory,并简单的返回true或false,这些静态方法接受的参数或者为一个字符,或者为一个string和该string中的一个字符的索引。
namespace CharStudy
{
class Program
{
static void Main( string [] args)
{
Console.WriteLine( char .IsDigit( ' 4 ' )); // 输出为true
Console.WriteLine( char .IsDigit( " heaiping " , 3 )); // 输出为false
Console.WriteLine( char .IsDigit( ' c ' )); // 输出为false
}
}
}
其他类似方法不再一一演示。
char还有一个静态方法GetNumericValue,返回一个字符对应的数值形式。
namespace CharStudy
{
class Program
{
static void Main( string [] args)
{
double d;
d = char .GetNumericValue( ' \u0033 ' );
Console.WriteLine(d.ToString()); // 3
d = char .GetNumericValue( ' \u00bc ' );
Console.WriteLine(d.ToString()); // 0.25
}
}
}
需要特殊说明的是ToUpper和ToLower,他们将字符床转换为相应的大写和小写形式。这些方法在做字符串转换时会调用到与线程相关的语言文化信息(System.Threading.Thread.CurrentCulture属性),或者可以用其重载函数直接传递以恶搞System.Globalization.CultrueInfo实例来指定文化信息,因为在不同的文化下大小写的方式是不一样的。
char类型提供的实力方法,Equal方法用于比较16位的unicode,CompareTo方法同样是根据unicode来比较的,这两种比较与语言文化没有关系。
.net提供了三种技巧用于数值和char实例之间的转换,分别为:
代码演示:
namespace CharStudy
{
class Program
{
static void Main( string [] args)
{
char c;
int n;
// 使用转型
c = ( char ) 65 ;
Console.WriteLine(c); // 显示A
n = ( int )c;
Console.WriteLine(n); // 65
// 使用COnvert
c = Convert.ToChar(n);
Console.WriteLine(c); // A
n = Convert.ToInt32(n); // 65
Console.WriteLine(n);
// 演示关于Convert对于超范围的检查
try
{
c = Convert.ToChar( 70000 ); // 超出16位
Console.WriteLine(c);
}
catch
{
Console.WriteLine( " overflow " );
}
// 使用IConvertible
c = ((IConvertible) 65 ).ToChar( null );
Console.WriteLine(c); // A
n = ((IConvertible)c).ToInt32( null );
Console.WriteLine(n); // 64
}
}
}
对于char的好多方法平时用的比较少,今天总算有个了解了,明天开始学习大头string。。。。。。。。。
书中自有颜如玉,书中自有黄金屋