zoukankan      html  css  js  c++  java
  • [CLR via C#]字符、字符串和文本处理

    • 字符

    在.NET Framework中,字符总是表示成16位Unicode代码值,简化了国际化应用程序的开发。

    数值类型与Char实例的相互转换:

    1.强制类型转换,效率最高,C#允许指定转换时是checked还是unchecked

    2.使用Convert类型

    3.使用IConvertible接口,效率最差

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace ConsoleApplication2
     8 {
     9     class Program
    10     {
    11         static void Main(string[] args)
    12         {
    13             Char c;
    14             int n;
    15             c = (Char)65; //强制类型转换
    16             Console.WriteLine(c);
    17             n = (int)c; //强制类型转换
    18             Console.WriteLine(n);
    19 
    20             c = unchecked((Char)(65536 + 65));
    21             Console.WriteLine(c);
    22 
    23             c = Convert.ToChar(65); //使用Convert类型
    24             Console.WriteLine(c);
    25             n = Convert.ToInt32(c);
    26             Console.WriteLine(n);
    27             try
    28             {
    29                 c = Convert.ToChar(70000);
    30                 Console.WriteLine(c);
    31             }
    32             catch(OverflowException e)
    33             {
    34                 Console.WriteLine("overflow...");
    35             }
    36 
    37             c = ((IConvertible)65).ToChar(null); //使用IConvertible转换
    38             Console.WriteLine(c);
    39             n = ((IConvertible)c).ToChar(null);
    40             Console.WriteLine(n);
    41             Console.ReadKey();
    42         }
    43     }
    44 }
    View Code
    •  字符串

    string s = "Hi" + " " + "world";

    上述代码中,所有字符串都是字面值,所以C#编译器能在编译时连接它们,最终只讲一个字符串“Hi world”放到模块的元数据中。对于非字面值使用+操作符,连接则在运行时进行,这样会在堆上创建多个字符串对象,影响性能。

    字符串时不可变的,它允许在一个字符串上执行各种操作而不实际地更改字符串;在操纵和访问字符串时不会发生线程同步问题;通过一个string对象共享多个完全一致的string内容,能减少系统中字符串的数量从而节省内存。

    FCL提供了StringBuilder类型对字符串和字符进行高效动态处理,可将StringBuilder想象成创建string对象的特殊构造器。

    无参ToString()方法存在两个问题:1.调用者无法控制字符串的格式,2.调用者不能方便的选择一种特定的语言文化来格式化字符串。为了使调用者能够选择格式和语言文化,类型应该实现System.IFormattable接口。

    public interface IFormattable
    {
        String ToString(String format,IFormatProvider formatProvider);
    }
  • 相关阅读:
    python网站开发准备ubuntu14.04安装mysql实现windows管理
    python 数据结构之二叉树
    python 数据结构之二分查找的递归和普通实现
    python 数据结构之归并排序
    python数据结构之希尔排序
    ctf study of jarvisoj reverse
    python数据结构之quick_sort
    堆与栈
    汇编整理
    js运算符
  • 原文地址:https://www.cnblogs.com/larry-xia/p/8472550.html
Copyright © 2011-2022 走看看