もちろん、私の答えはlinqの答えほど魅力的ではありませんが、このold school
方法を投稿したいと思います。
void Main()
{
List<string> result = new List<string>();
string inp = "USD 1.23 1.12 1.42 EUR 0.2 0.3 0.42 JPY 1.2 1.42 1.53";
while(true)
{
int pos = IndexOfN(inp, " ", 4);
if(pos != -1)
{
string part = inp.Substring(0, pos);
inp = inp.Substring(pos + 1);
result.Add(part);
}
else
{
result.Add(inp);
break;
}
}
}
int IndexOfN(string input, string sep, int count)
{
int pos = input.IndexOf(sep);
count--;
while(pos > -1 && count > 0)
{
pos = input.IndexOf(sep, pos+1);
count--;
}
return pos ;
}
編集:入力文字列の数値を制御できない場合(たとえば、一部のお金に1つまたは2つの値しかない場合)、入力文字列の4つのブロックで正しくサブストリングする方法はありません。正規表現に頼ることができます
List<string> result = new List<string>();
string rExp = @"[A-Z]{1,3}(\d|\s|\.)+";
// --- EUR with only two numeric values---
string inp = "USD 1.23 1.12 1.42 EUR 0.2 0.42 JPY 1.2 1.42 1.53";
Regex r = new Regex(rExp);
var m = r.Matches(inp);
foreach(Match h in m)
result.Add(h.ToString());
このパターンは、小数点記号としてコンマを含む数字と数字を含まない通貨記号も受け入れます( "GPB USD 1,23 1,12 1.42"
string rExp = @"[A-Z]{1,3}(,|\d|\s|\.)*";
RegEx式言語-クイックリファレンス