我正在使用C#4.0并且遇到过这样一种情况:我必须每四个单词拆分整个字符串并将其存储在List对象中.所以假设我的字符串包含:"USD 1.23 1.12 1.42 EUR 0.2 0.3 0.42 JPY 1.2 1.42 1.53",结果应该是:
USD 1.23 1.12 1.42
EUR 0.2 0.3 0.42
JPY 1.2 1.42 1.53
Run Code Online (Sandbox Code Playgroud)
它应保存到List对象中.我尝试了以下内容
List<string> test = new List<string>(data.Split(' ')); //(not working as it splits on every word)
Run Code Online (Sandbox Code Playgroud)
带着一点Linq魔法:
var wordGroups = text.Split(' ')
.Select((word, i) => new { Word = word, Pos = i })
.GroupBy(w => w.Pos / 4)
.Select(g => string.Join(" ", g.Select(x=> x.Word)))
.ToList();
Run Code Online (Sandbox Code Playgroud)
当然,我的回答并不像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 ;
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果输入字符串上的数字没有控制(例如,如果一些钱只有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());
Run Code Online (Sandbox Code Playgroud)
此模式也接受带逗号的数字作为小数分隔符和没有任何数字的货币符号("GPB USD 1,23 1,12 1.42"
string rExp = @"[A-Z]{1,3}(,|\d|\s|\.)*";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |