LoginSignup
0
1

More than 3 years have passed since last update.

C#の基礎知識 No.1

Last updated at Posted at 2020-01-21

今後必要になってくると思うので、Microsoftが出しているチュートリアルの内容を議事録としてまとめました。

文字列の処理

二つの方法がある。

Foobar.cs
string friend = "Tom";
Console.WriteLine("Hello" + friend);

この方法だとエラーを吐くことなく出力が可能ではあるが、一回一回「+」を入れなければならないので面倒。
そのため、

Foobar.cs
string friend = "Tom";
Console.WriteLine($"Hello {friend}");

でも同じ結果が出力される。
文字列の開始引用符の前に$を入れることにより、文字列内に変数が入れることが可能。

文字列の追加操作

トリミング

無駄な空白がある文字列のトリミングを行うことも可能。

Foobar.cs
// 以下のような変数を定義すると
string food = "     apple     ";
Console.WriteLine($"[{food}]");

// このように出力される
 [     apple     ]

そのため、Trimメソッドを用いる

Foobar.cs
string trimFood = food.Trim();
Console.WriteLine($"[{trimFood}]");

 [apple]

// 先頭のみトリミング
trimFood = food.TrimStart();
Console.WriteLine($"[{trimFood}]");

 [apple     ]

// 末尾のみトリミング
trimFood = food.TrimEnd();
Console.WriteLine($"[{trimFood}]");

 [     apple]

置き換え

文字列を置き換えすることも可能。

Foobar.cs
string fav = "Like Movie";
Console.WriteLine(fav);

 Like Movie

//置き換えを行う時はReplaceメソッドを使用する
fav = fav.Replace("Movie", "Running");
Console.WriteLine(fav);

 Like Running

文字サイズ変更

全てを大文字・小文字に変換することも可能。

Foovar.cs
Console.WriteLine(fav.ToUpper());

 LIKE RUNNING

Console.WriteLine(fav.ToLower());

 like runnning

文字列の検索

文字列内に検索文字列が含まれているかどうかを調べることが可能。
出力はTrueFalseのどちらかによるboolean型
メソッドは3種類あり各々に違いがある。

Containts : 文字列のどこかに検索文字列があればTrueを返し、なければFalseを返す
StartsWith : 文字列の先頭に検索文字列があればTrueを返す
EndsWith : 文字列の末尾に検索文字列があればTrueを返す

Foobar.cs
string intro = "I have no friends, but live strongly";
// Contains
Console.WriteLine(intro.Containts("friends"));
Console.WriteLine(intro.Containts("foods"));

// StartsWith
Console.WriteLine(intro.StartsWith("I"));
Console.WriteLine(intro.StartsWith("friends"));

// EndsWith
Console.WriteLine(intro.EndsWith("stringly"));
Console.WriteLine(intro.EndsWith("friends"));

 True
 False

 True
 False

 True
 False
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1