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

文字列の特定文字での分割、配列/Listの連結(string.Splitとstring.Joinの使い方)

Posted at

0.0  はじめに

string.Splitをつかうと、文字列を指定した文字で分割することができます。
string.Joinは配列やListの要素を連結してくれます。配列をログに出す時などに使うと便利です。

1.0  String.Splitでの文字列の分割

C# Test.cs
// 文字列の定義
string momotaro = "おじいさんは、やまに、しばかりに、いきました。";
        
// 文字列を特定文字で分割する(ここでは 「、」)
// 分割した文字列は配列に代入
string[] strArray = momotaro.Split('、');

// 分割した文字列を1文づつコンソールに表示
for (int i = 0; i < strArray.Length; i++) {
    Debug.Log(strArray[i]);
}

image.png

1.1  2つ以上の文字での分割

2つ以上の文字での分割も可能です。
char[] splitChar = {'、', '。'};のように分割に使用する文字を定義
momotaro.Split(splitChar);
(「、」もしくは「。」のどちらかで分割する)

2.0  String.Joinでの文字列の連結

C# Test.cs
// 数字の羅列(文字列)を定義
string suji = "0,1,2,3,4";

// 文字列を特定文字で分割する(ここでは 「,」)
// 分割した文字列は配列に代入
string[] strArray = suji.Split(',');

// 分割した数字を1文字づつコンソールに表示
for (int i = 0; i < strArray.Length; i++) {
    Debug.Log(strArray[i]);
}

// 数字を1行で表示
// " と "で文字列(数字)を連結
Debug.Log(string.Join(" と ", strArray));


// おまけ
// 数字(int)の格納用
List<int> intList = new List<int>();
        
// 文字列(string)を数字(int)に変換
for (int i = 0; i < strArray.Length; i++) {
    intList.Add(int.Parse(strArray[i]));
}

// 変換した数字のはListを1行で表示
Debug.Log(string.Join(" + ", intList));

// 数字の合計
int sum = 0;
for (int i = 0; i < intList.Count; i++) {
    sum += intList[i];
}
 Debug.Log("数字の合計は " + sum + " です。");

image.png

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