1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# 文字列の部分変更、削除

Posted at

##0.0 はじめに
string型の文字列はchar型の集合体、リストの様な形で取り扱えるので目的の文字列もしくは文字を削除するのは非常に簡単です。(以下、文字1字も文字列として扱います。

##1.0 Replace関数
Replace関数はその名の通り、文字列を入れ換えるときに使います。第一引数に検索する文字列、第二引数に置き換える文字列を入れます。この第二引数に""(空文字)を指定すれば文字列を削除することが出来ます。

👍️ポイント
Replace関数はもとの文字列を変更するものではありません。もとの文字列を変更したい場合はstr=str.Replace("abc","")のように置き換えたものをもとの文字列に代入しましょう。

Test.cs
string str0 = "abcde";
string str1 = str0.Replace("de", "fgh"); // deをfghに変える
string str2 = str0.Replace("bc", ""); // bcを削除する
Debug.Log($"str0は {str0} です");
Debug.Log($"str1は {str1} です");
Debug.Log($"str2は {str2} です");

image.png

##2.0 Trim関数
Trim関数は前後の空白を削除することが出来ます。

👍️ポイント
文字列途中の空白は削除できません

Test.cs
string str0 = " abc de "; // 前後、真ん中に空白あり
string str1 = str0.Trim(); // 前後の空白を取り除く
string str2 = str0.TrimStart(); // 前の空白を取り除く
string str3 = str0.TrimEnd(); // 後の空白を取り除く
Debug.Log($"str0は{str0}です");
Debug.Log($"str1は{str1}です");
Debug.Log($"str2は{str2}です");
Debug.Log($"str3は{str3}です");

image.png

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?