1
2

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 5 years have passed since last update.

[C#覚え書き]文字列をSplit→データ型指定してArrayやListに変換

Posted at

using

using System.Linq;
using System.Collections.Generic;

文字列を分割(Split)

文字列の分割にはSplitを使用.
string Str = "1,2,3,4,5,6,7,8";//カンマ区切りなら
string[] StrAry = Str.Split(',');

Str = "1 2 3 4 5 6 7 8";//スペース区切りなら
StrAry = Str.Split(' ');

文字列を数値に変換(Parse)

string Str = "1";
int val = int.Parse(Str);

ただし、変換できないと例外が発生するのでデータのValidationをしっかりするか、エラー処理を記載すること

string Str = "1asdf";
//int val = int.Parse(Str);//←エラー
bool boo = int.TryParse(str,out int val);//←エラーは起きない
//trueなら変換し、outで結果が出力される

Split & LINQを使って配列に変換

string Str = "1,2,3,4,5,6,7,8";
var ary = Str.Split(',').Select(a => int.Parse(a));
//または
int[] ary = Str.Split(',').Select(a => int.Parse(a)).ToArray();//個人的には明示したほうが好き

List型なら

string Str = "1,2,3,4,5,6,7,8";
List<int> ary = Str.Split(',').Select(a => int.Parse(a)).ToList();

List型 doubleなら

string Str = "1.92,2.13,3.14,4.3453,5.134,6.1341,7.535,8.5343";
List<double> ary = Str.Split(',').Select(a => double.Parse(a)).ToList();

入力がdoubleで四捨五入してint配列なら

string Str = "1.92,2.13,3.14,4.3453,5.134,6.1341,7.535,8.5343";
int[] ary = Str.Split(',').Select(a => (int)Math.Round(double.Parse(a))).ToArray();

入力が怪しいときはどうすれば?

どうすればスマートなのでしょう?

無理やりやってみる.
string Str = "1,2,3,4,5,6,7asd,8";
int[] ary = Str.Split(',').Select(a => int.TryParse(a, out int v) ? v : -1).ToArray();//駄目なときは-1を出力してみた

まだまだLINQは苦手です。
(初投稿、慣れないことやって肩凝りました)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?