在字符串中查找单词的出现次数,并将其与接下来的4个字符C#一起打印

时间:2014-09-16 14:27:00

标签: c# substring

我有这个字符串的问题=“Leeds United 1 Chelsea 0,Arsenal 1 Leeds United 1,Leeds United 3 Fulham 1,Liverpool 2 Leeds United 1,Swansea 2 Leeds United 4”

我希望每次出现“Leeds United”这个词加上旁边的分数,然后打印出那些分数。我已经尝试过使用子串,但是我不确定如何对其进行编码以使其沿着4-5个位置

4 个答案:

答案 0 :(得分:3)

问题不是很明确,但如果您需要在Leeds United文本之后提取分数 - 这可以通过正则表达式轻松完成:

string source = "Leeds United 1 Chelsea 0, Arsenal 1 Leeds United 1, Leeds United 3 Fulham 1, Liverpool 2 Leeds United 1, Swansea 2 Leeds United 4";

var matches = Regex.Matches(source, @"Leeds United \d+");
foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[0].Value);
}

或者,如果您只需要得分号码:

var matches = Regex.Matches(source, @"Leeds United (\d+)"); 
foreach(Match match in matches) 
{
   Console.WriteLine(match.Groups[1].Value); 
}

答案 1 :(得分:2)

您可以使用LINQ查询和String.Split s:

var leedsScores = str.Split(',')
    .Select(s => s.Split(new[] { "  " }, StringSplitOptions.RemoveEmptyEntries))
    .Where(arr => arr.Length >= 2)
    .Where(arr => arr.Any(team => team.Contains("Leeds United")))
    .Select(arr => arr.First(team => team.Contains("Leeds United")).Split(' ').Last());

foreach (string leedsScore in leedsScores)
    Console.WriteLine(leedsScore);

打印出来:

1
1
3
1
4

答案 2 :(得分:1)

您的问题不清楚(提供所需的结果);你的意思是那样的( Linq ):

String source = "Leeds United 1 Chelsea 0, Arsenal 1 Leeds United 1, Leeds United 3 Fulham 1, Liverpool 2 Leeds United 1, Swansea 2 Leeds United 4";

String result = String.Join(Environment.NewLine, source
  .Split(',')
  .Where(line => line.Contains("Leeds United"))
  .Select(line => line.Trim()));

result

  Leeds United 1 Chelsea 0
  Arsenal 1 Leeds United 1
  Leeds United 3 Fulham 1
  Liverpool 2 Leeds United 1
  Swansea 2 Leeds United 4

答案 3 :(得分:0)

试试这个:

        var totalResults = new List<string>();
        var s = " Leeds United 1 Chelsea 0, Arsenal 1 Leeds United 1, Leeds United 3 Fulham 1, Liverpool 2 Leeds United 1, Swansea 2 Leeds United 4";
        var sarr = s.Split(',');
        foreach (var i in sarr)
        {
            var substring = i.Substring(i.IndexOf("Leeds United"),14);
            totalResults.Add(substring);
        }

对于得分高于9的游戏不适用,但对于利兹联队,我怀疑存在任何危险:P(编辑为“利兹联队”)