簡體   English   中英

如何在c#中每四個單詞拆分一個字符串?

[英]How to split a string at every four words in c#?

我正在使用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

它應保存到List對象中。 我嘗試了以下內容

List<string> test = new List<string>(data.Split(' ')); //(not working as it splits on every word)

帶着一點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();

當然,我的回答並不像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表達式語言 - 快速參考

最簡單的方法是首先將每個單詞拆分成一個列表,然后編寫一個小循環,重新組合每組四個單詞。

反應式框架人員有一堆IEnumerable<T>的擴展。 其中之一就是Buffer ,它可以做到你想要的那么簡單。

這里是:

var text = "USD 1.23 1.12 1.42 EUR 0.2 0.3 0.42 JPY 1.2 1.42 1.53";
var result = text.Split(' ').Buffer(4);

這給了:

結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM