「C#」カンマで文字列を分割するサンプル
関数
public string[] Split (params char[]? separator);
指定された区切り文字に基づいて文字列を部分文字列に分割します。
戻り値 このインスタンスを separator の 1 つ以上の文字で区切った部分文字列を要素に格納する配列。
書式
string 変数名 = 値
string[] 配列名 = 文字列変数名.Split(new char[] { ',’ })
結果を取得する方法
from 変数名 in 配列名 select 変数名
配列名.Select(変数名 => 変数名))
使用例
using System;
using System.Collections.Generic;
using System.Linq;
namespace arkcft
{
class Program
{
static void Main(string[] args)
{
string target = "study,skill,become,smart,hard";
// カンマで分割
string[] resArr = target.Split(new char[] { ',' });
Console.WriteLine(" for in文で文字列を分割する結果(linq)");
Console.WriteLine(String.Join(" ", from ele in resArr select ele));
Console.WriteLine(" Selectで文字列を分割する結果(ラムダ演算子)");
// ラムダ演算子
Console.WriteLine(String.Join(" ", resArr.Select(ele => ele)));
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace arkcft
{
class Program
{
static void Main(string[] args)
{
string target = "study,skill,become,smart,hard";
// カンマで分割
string[] resArr = target.Split(new char[] { ',' });
Console.WriteLine(" for in文で文字列を分割する結果(linq)");
Console.WriteLine(String.Join(" ", from ele in resArr select ele));
Console.WriteLine(" Selectで文字列を分割する結果(ラムダ演算子)");
// ラムダ演算子
Console.WriteLine(String.Join(" ", resArr.Select(ele => ele)));
Console.ReadKey();
}
}
}
using System; using System.Collections.Generic; using System.Linq; namespace arkcft { class Program { static void Main(string[] args) { string target = "study,skill,become,smart,hard"; // カンマで分割 string[] resArr = target.Split(new char[] { ',' }); Console.WriteLine(" for in文で文字列を分割する結果(linq)"); Console.WriteLine(String.Join(" ", from ele in resArr select ele)); Console.WriteLine(" Selectで文字列を分割する結果(ラムダ演算子)"); // ラムダ演算子 Console.WriteLine(String.Join(" ", resArr.Select(ele => ele))); Console.ReadKey(); } } }
実行結果
for in文で文字列を分割する結果(linq)
study skill become smart hard
Selectで文字列を分割する結果(ラムダ演算子)
study skill become smart hard
for in文で文字列を分割する結果(linq)
study skill become smart hard
Selectで文字列を分割する結果(ラムダ演算子)
study skill become smart hard
for in文で文字列を分割する結果(linq) study skill become smart hard Selectで文字列を分割する結果(ラムダ演算子) study skill become smart hard