转 String常用方法回顾

代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace StringTest
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
//格式化输出
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd"));
            Console.WriteLine(
string.Format("{0} 在{1:yyyy年MM月dd日}到达北京.""小王", DateTime.Now));
            
double d = 123.456789;
            Console.WriteLine(d.ToString(
"C3")); 

            
string s = "1,2,3,4,5,6";
            
string[] s2 = s.Split(','); //注意是''
            foreach (string i in s2)
            {
                Console.WriteLine(i);
            }

            
//指定符号连接
            string join = string.Join("-", s2);
            Console.WriteLine(join);

            
//String 与 StringBuilder 效率比较
            DateTime before = DateTime.Now;
            
string a = "aaa";
            
for (int i = 0; i < 20000; i++)
            {
                a 
+= i;
            }
            Console.WriteLine(
"String相加循环所花费的时间为{0}", DateTime.Now - before);

            DateTime start 
= DateTime.Now;
            StringBuilder sb 
= new StringBuilder("aaa");
            
for (int i = 0; i < 20000; i++)
            {
                sb.Append(i);
            }
            Console.WriteLine(
"StringBuilder相加循环所花费的时间为{0}", DateTime.Now - start);

            
//类型转换
            string st = "123e";
            
int dd;
            
if (int.TryParse(st, out dd))
            {
                Console.WriteLine(dd);
            }
            
else
            {
                Console.WriteLine(
"请输入正确的数字!");
            }

            
//判断字符串是否为空
            string em = "";
            
if (string.IsNullOrEmpty(em))
            {
                Console.WriteLine(
"em是空字符串!");
            }

            
//截取
            string tr = "---bcd---";
            
string end = tr.Trim('-');
            Console.WriteLine(
string.Format("{0}:长度为{1}", end, end.Length));

            
//比较  ToUpper()经过优化,效率比较高
            string yz = "aBC";
            
string sz = "Abc";
            Console.WriteLine(yz.ToUpper() 
== sz.ToUpper());
            
//MVP推荐使用
            Console.WriteLine(string.Compare(yz, sz, true== 0);

            
//正则表达式
            Regex re = new Regex("[a-zA-Z]+", RegexOptions.None);
            
string[] lines = re.Split("12r4t");
            
foreach (string line in lines)
            {
                Console.WriteLine(line);
            }

            MatchCollection mc 
= re.Matches("t45yu");
            
foreach (Match ma in mc)
            {
                Console.WriteLine(ma);
            }
            Console.ReadKey();
        }
    }
}

 

看到别人总结的,自己也回顾一下.
posted @ 2010-03-02 10:56  smodi  阅读(324)  评论(0编辑  收藏  举报