normalian blog

Let's talk about Microsoft Azure, ASP.NET and Java!

stringクラスのメソッドを使ってみる

どう書く?org 辺りだと、この辺のメソッドをちょくちょく使うことがあるのでちょっと再確認。

string.Join メソッド

結合文字列を指定し、文字列をくっつける。具体的には以下の様に使用する。

Console.WriteLine(string.Join(",", new string[] { "a", "b", "c", "d" }));
//a,b,c,d

結合する範囲も指定できる。

Console.WriteLine(string.Join(",", new string[] { "a", "b", "c", "d", "e", "f", "g" }, 2, 3));
//c,d,e

string.IsNullOrEmpty メソッド

文字列が NULL or 空文字列 な事をチェックしてくれる。もう以下の様なコードを書かなくてよい。

string str = SomeMethod();
if( string!=null && string!=string.Empty )
{
なんかの処理
}

ためしに使ってみたのが以下の例

Console.WriteLine(string.IsNullOrEmpty(null));
//True
Console.WriteLine(string.IsNullOrEmpty(""));
//True
Console.WriteLine(string.IsNullOrEmpty(@""));
//True
Console.WriteLine(string.IsNullOrEmpty(string.Empty));
//True
Console.WriteLine(string.IsNullOrEmpty("test"));
//False