黑馬程序員-.NET基礎之日期和字符串處理

------- Windows Phone 7手機開發.Net培訓、期待與您交流! -------

 

    日期和字符串的處理無論是開發什麼應用,基本上是不可或缺的,或許我現在還沒有進行黑馬的視頻面試,但我可以肯定的說,這是測試時必問的知識點,關於這個知識點,難度幾乎沒有,但需要我們很細心的去學習。現將自己整理好的筆記記錄如下。

 

一、 日期和時間處理

日期和時間的使用示例:打印當年當月的日曆。

using System;
namespace CSharpPractice.RegularExpressions
{
    class CalendarTest
    {
        static void Main(string[] args)
        {
            const string s4 = "    ";          //空4格
            int nYear = DateTime.Today.Year;   //當前的年份
            int nMonth = DateTime.Today.Month; //當前的年份
            // 打印當年當月的日曆
            DateTime d1 = new DateTime(nYear, nMonth, 1);
            Console.WriteLine("{0}/{1}", d1.Year, d1.Month);
            Console.WriteLine("SUN MON TUE WED THU FRI SAT");
             // 獲取當年當月1號的星期
int iWeek = (int)d1.DayOfWeek;  
             // 獲取當年當月最後1天的日
int iLastDay = d1.AddMonths(1).AddDays(-1).Day; 
            for (int i = 0; i < iWeek; i++) Console.Write(s4);
            for (int i = 1; i <= iLastDay; i++)
            {  // 對應星期(Sun,Mon,…,Sat)打印日
                Console.Write(" {0:00} ", i);
                if ((i + iWeek) % 7 == 0) Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}


 

二、字符串處理

    C#字符串是Unicode字符的有序集合,Unicode字符使用UTF-16進行編碼,編碼的每個元素的數值都用一個System.Char對象表示。使用System.String和System.Text.StringBuilder,可以動態構造自定義字符串,執行許多基本字符串操作,如從字節數組創建新字符串,比較字符串的值和修改現有的字符串等等。C#字符串是使用string關鍵字聲明的一個字符數組。字符串是使用引號聲明的。

2.String類

String 對象稱爲不可變的(只讀),因爲一旦創建了該對象,就不能修改該對象的值。有些字符串操作看來似乎修改了 String 對象,實際上是返回一個包含修改內容的新 String 對象。如果需要修改字符串對象的實際內容,可以使用 System.Text.StringBuilder 類。下面是字符串的使用示例。

using System;
using System.Collections;
namespace CSharpPractice.RegularExpressions
{
    class Vowels
    {
        static void Main(string[] args)
        {
//            String str = @"A string is a sequential collection of Unicode characters that is used to represent text. 
//                        A String object is a sequential collection of System.Char objects that represent a string. 
//                        The value of the String object is the content of the sequential collection, and that value is immutable.";
            int countA = 0, countE = 0, countI = 0, countO = 0, countU = 0, countAll = 0;
            Console.WriteLine("請輸入字符串:");
            String str = Console.ReadLine();
            str = str.ToUpper();
            char[] chars = str.ToCharArray();
            foreach (char ch in chars)
            {
                countAll++;
                switch (ch)
                {
                    case 'A':
                        countA++;
                        break;
                    case 'E':
                        countE++;
                        break;
                    case 'I':
                        countI++;
                        break;
                    case 'O':
                        countO++;
                        break;
                    case 'U':
                        countU++;
                        break;
                    default:
                        break;
                }
            }
            Console.WriteLine("所有字母的總數爲:{0}", countAll);
            Console.WriteLine("元音字母出現的次數和頻率分別爲:");
            Console.WriteLine("A:\t{0}\t{1:#.00%}", countA, countA * 1.0 / countAll);
            Console.WriteLine("E:\t{0}\t{1:#.00%}", countE, countE * 1.0 / countAll);
            Console.WriteLine("I:\t{0}\t{1:#.00%}", countI, countI * 1.0 / countAll);
            Console.WriteLine("O:\t{0}\t{1:#.00%}", countO, countO * 1.0 / countAll);
            Console.WriteLine("U:\t{0}\t{1:#.00%}", countU, countU * 1.0 / countAll);
            Console.ReadKey();
        }
    }
}


 

3.StringBuilder類

    StringBuilder類表示值爲可變字符序列的類似字符串的對象,但創建其實例後可以通過追加、移除、替換或插入字符而對它進行修改。StringBuilder類創建一個字符串緩衝區,用於在程序執行大量字符串操作時提供更好的性能。下面是StringBuilder類常用方法和屬性的使用示例。

using System;
using System.Text;
namespace CSharpPractice.RegularExpressions
{
    public sealed class StringBuilderTest
    {
        static void Main()
        {
            // 創建一個StringBuilder對象,使其最多可以存放50個字符.
            // 初始化StringBuilder對象爲:"ABC".
            StringBuilder sb = new StringBuilder("ABC", 50);

            // 在StringBuilder對象後追加3個字符 (D, E, and F).
            sb.Append(new char[] { 'D', 'E', 'F' });

            //在StringBuilder對象後追加格式化字符串.
            sb.AppendFormat("GHI{0}{1}", 'J', 'k');

            // 顯示StringBuilder對象的長度和內容.
            Console.WriteLine("{0} chars,內容爲: {1}", sb.Length, sb.ToString());

            // 在StringBuilder對象最前面插入字符串"Alphabet---".
            sb.Insert(0, "Alphabet---");

            // 將所有的小寫字母k替換爲大寫字母K.
            sb.Replace('k', 'K');

            //顯示StringBuilder對象的長度和內容.
            Console.WriteLine("{0} chars,內容爲: {1}", sb.Length, sb.ToString());

            Console.ReadLine();
        }
    }
}


 

4.字符編碼

默認情況下,公共語言運行庫使用UTF-16編碼(Unicode轉換格式,16位編碼形式)表示字符。字符編碼的使用示例。

using System;
using System.Text;
namespace CSharpPractice.RegularExpressions
{
    class ConvertExampleClass
    {
        static void Main()
        {
            string unicodeString = "本字符串包含unicode字符Pi(\u03a0)";
            // 創建2個不同的編碼:ASCII和UNICODE.
            Encoding ascii = Encoding.ASCII;
            Encoding unicode = Encoding.Unicode;
            // 將string轉換爲byte[].
            byte[] unicodeBytes = unicode.GetBytes(unicodeString);
            // 執行一個編碼到另一個編碼的轉換.
            byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
            // 將byte[] 轉換爲char[] ,再轉換爲string.
            // 演示GetCharCount/GetChars轉換方法的使用,注意其中的細微差別.
            char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
            ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
            string asciiString = new string(asciiChars);
            // 顯示字符串轉換之前和轉換之後的內容.
            Console.WriteLine("原始string(Unicode):{0}", unicodeString);
            Console.WriteLine("轉換後的string(Ascii):{0}", asciiString);
            Console.ReadLine();
        }
    }
}


 

 

三、正則表達式

正則表達式是由普通字符(例如:字符 a 到 z)以及特殊字符(稱爲元字符,例如:.、\、?、*、+、{、}、(、)、[ 或 ])組成的文字模式。該模式描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作爲一個模板,將某個字符模式與所搜索的字符串進行匹配。

2.正則表達式類

System.Text.RegularExpressions命名空間提供對字符進行編碼和解碼的最常用的類,包括Regex類、Match類、MatchCollection類、GroupCollection/Group類、CaptureCollection/ Capture類。正則表達式的使用示例

using System;
using System.Text.RegularExpressions;
namespace CSharpPractice.RegularExpressions
{
class RegularExpressionEmail
{
    static void Main(string[] args)
    {   // 有效的電子郵件正則表達式格式
        String pattern = 
@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        String strIn1 = "[email protected]";  // 有效的電子郵箱
        bool b1 = Regex.IsMatch(strIn1, pattern);
        String strIn2 = "hjiang.yahoo.com";   // 無效的電子郵箱
        bool b2 = Regex.IsMatch(strIn2, pattern);
        Console.WriteLine("[email protected] 是有效的電子郵件格式嗎?"+b1);
        Console.WriteLine("hjiang.yahoo.com 是有效的電子郵件格式嗎?" +b2);
        Console.ReadKey();
    }
}
}


 

------- Windows Phone 7手機開發.Net培訓、期待與您交流! -------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章