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);
    }
  • 相关阅读:
    Java 简单算法--打印乘法口诀(只使用一次循环)
    Java简单算法--求100以内素数
    ubuntu 16.04 chrome flash player 过期
    java 网络API访问 web 站点
    java scoket (UDP通信模型)简易聊天室
    leetcode1105 Filling Bookcase Shelves
    leetcode1140 Stone Game II
    leetcode1186 Maximum Subarray Sum with One Deletion
    leetcode31 Next Permutation
    leetcode834 Sum of Distances in Tree
  • 原文地址:https://www.cnblogs.com/larry-xia/p/8472550.html
Copyright © 2011-2022 走看看