Split
というメソッドを使うことで簡単に文字列の分割ができるそうです。使い方は次のような感じです。
コンマ「
,
」かハイフン「-
」で分割using System;
class Example1
{
static public void Main()
{
string str = "one,two-three";
char[] sep = { ',', '-' };
string[] ar = str.Split(sep, StringSplitOptions.None);
foreach(string s in ar) {
Console.WriteLine(s);
}
}
}
実行結果
one
two
three
連続した3つのハイフン「
---
」で分割using System;
class Example2
{
static public void Main()
{
string str = "one---two-three";
string[] sep = { "---" };
string[] ar = str.Split(sep, StringSplitOptions.None);
foreach(string s in ar) {
Console.WriteLine(s);
}
}
}
実行結果
one
two-three
他にも正規表現を使って分割したりできるみたいです。
リンク
String.Split Method (System) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.string.split