黑马程序员-.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 = "hjiang@yahoo.com";  // 有效的电子邮箱
        bool b1 = Regex.IsMatch(strIn1, pattern);
        String strIn2 = "hjiang.yahoo.com";   // 无效的电子邮箱
        bool b2 = Regex.IsMatch(strIn2, pattern);
        Console.WriteLine("hjiang@yahoo.com 是有效的电子邮件格式吗?"+b1);
        Console.WriteLine("hjiang.yahoo.com 是有效的电子邮件格式吗?" +b2);
        Console.ReadKey();
    }
}
}


 

------- Windows Phone 7手机开发.Net培训、期待与您交流! -------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值