2010-11-25 13:36:40Chris C.S Huang

[C#] 字串處理

1. 字串格式-Format
using  System;       
class  MainClass  {       

public  static  void  Main()  {   

        double  v  =  17688.65849;   

        double  v2  =  0.15;   

        int  x  =  21;    

        string  str  =  String.Format("{0:F2}",  v);//浮點數       

        Console.WriteLine(str);       

        str  =  String.Format("{0:N5}",  v);    //數字    

        Console.WriteLine(str);              

        str  =  String.Format("{0:e}",  v);    //科學記號         

        Console.WriteLine(str);       

        str  =  String.Format("{0:r}",  v);       

        Console.WriteLine(str);              

        str  =  String.Format("{0:p}",  v2);    //百分比     

        Console.WriteLine(str);       

        str  =  String.Format("{0:X}",  x);  //十六進位      

        Console.WriteLine(str);       

        str  =  String.Format("{0:D12}",  x);    //十進位

        Console.WriteLine(str);         

        str  =  String.Format("{0:C}",  189.99); //貨幣  

        Console.WriteLine(str);   

    }   

}   

17688.66
17,688.65849
1.768866 e+004
17688.65849
15.00%
15
000000000021
NT$189.99
2. 清除字串 - Empth
using System;
namespace ConsoleApplication1
{ 
    class Program
    {
      static void Main (string[] args)
      {
        string name = "Chris Huang";
        Console.WriteLine("Name = {0}", name);
        name = String.Empty;
        Console.WriteLine("Name = {0}", name);
        Console.Read();
      }
    }
}
輸出結果:
Name = Chris Huang
Name = 

 
3. 字串長度 Length
using System;
namespace Prog06_06
{
 class MainProg
 {
  static void Main(string[] args)
  {
   string  str = "Chris Huang";
   int     stringLen = 0;
   Console.WriteLine("String  = {0}", str);
   stringLen = str.Length;
   Console.WriteLine("String Length = {0}",stringLen);
   Console.WriteLine();
   Console.WriteLine("Press Enter key to Exit!!");
   Console.Read();
  }
 }
}
輸出結果
String = Chris Huang
String Length = 11
Press Enter key to Exit!!
 
4. 字串分割-Split
using System;
class Program{    
   static void Main()    
     {        
        string FileName = "tree.jpg";               
        string[] words = FileName.Split('.');        
        foreach (string word in words)        
           {            
             Console.WriteLine(word);        
           }    
     }
}
 
輸出結果
tree
jpg
 
 
5. 字串陣列宣告 - string[] 
string[] color =  new string[2] {"Black", "White"};
 
 
6. 子字串 - Substring
 
語法:string string.Substring(int StartIndex, int Length);
 
   static void Main(string[] args)
   {
            string str = "Collections";
            string substr = str.Substring(str.Length - 6, 6);
            Console.WriteLine(substr);
            Console.Read();
   }
   
輸出結果:
Substring = ctions
參考資料:
http://www.navioo.com/csharp/examples/String_113.dhtml