NET4.0新功能之String.IsNullOrWhiteSpace() 方法

來源:互聯網
上載者:User

在.NET Framework 4.0  中新增加了一些很方便的功能,比如:System.Dynamic支援動態語言運行時、System.Numerics.Complex 複數、System.Numerics.BigInteger 大數、System.Tuple 對象、遍曆檔案夾下檔案夾和檔案的新方法Directory.EnumerateDirectories、Directory.EnumerateFiles、Directory.EnumerateFileSystemEntries等,詳細的新功能列表可以參考下面的連結:

http://msdn.microsoft.com/en-us/library/ms171868(VS.100).aspx

同時,還否定了一些原先的功能,這些過時的內容可以參考

http://msdn.microsoft.com/en-us/library/ee461502%28VS.100%29.aspx

下面就是.NET 4.0中新增加的String.IsNullOrWhiteSpace() 方法,方便使用者對字串進行處理。

C# 代碼using System;
class TestNET4
{
  staticvoid Main()
  {
    String[] TestString = { null, String.Empty, "", " ", "abc ", "/t", "/r/n", "/v", "/f", "/a" };
    for (int i =0; i < TestString.Length; i++)
    {
      String temp = TestString[i];
      if (temp ==null)
      {
        Console.WriteLine(" null IsNullOrWhiteSpace = "
                    + String.IsNullOrWhiteSpace(temp).ToString());
      }
      else
      {
        Console.WriteLine(temp +" Length="+ temp.Length.ToString()
              +" IsNullOrWhiteSpace = "
              + String.IsNullOrWhiteSpace(temp).ToString());
      }
    }
  }
}

程式執行結果:

 null IsNullOrWhiteSpace = True
 Length=0 IsNullOrWhiteSpace = True
  Length=1 IsNullOrWhiteSpace = True
  Length=1 IsNullOrWhiteSpace = True
abc  Length=4 IsNullOrWhiteSpace = False
         Length=1 IsNullOrWhiteSpace = True

 Length=2 IsNullOrWhiteSpace = True
Length=1 IsNullOrWhiteSpace = True
Length=1 IsNullOrWhiteSpace = True
 Length=1 IsNullOrWhiteSpace = False

 

IsNullOrWhiteSpace方法的具體實現代碼為:

C# 代碼publicstaticbool IsNullOrWhiteSpace(string value)
{
    if (value !=null)
    {
        for (int i =0; i < value.Length; i++)
        {
            if (!char.IsWhiteSpace(value[i]))
            {
                returnfalse;
            }
        }
    }
    returntrue;
}

所以,他是通過判斷char.IsWhiteSpace方法來實現的,有些特殊字元也被當作空白字元,這一點特別注意注意,比如全形空格。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.