C#。如何在较大的字符串中找到一个小字符串?

时间:2016-06-21 14:26:53

标签: c# string

我有一个像这样的输入字符串:

  

Tshirt39Tshirt39Tshirt15Jean39Jean52Jean52Jean52

然后我想要一个输出:

  

Tshirt39:2个单位
  Tshirt15:1单位
  Jean39:1单位
  Jean52:3单位

  

T恤:15 + 39 + 39   让:39 + 52 + 52 + 52"

这是我的代码:

Console.WriteLine("In put data:\n");
string total = Console.ReadLine();
// In put to string total: "Tshirt39Tshirt39Tshirt15Jean39Jean52Jean52Jean52"
string b = "Tshirt39" ;
int icount=0;

for (int i=0;i<total.Length;i++)
{
   if ( total.Contains(b));
   {
       icount+=1;
   }
}

Console.WriteLine();
Console.WriteLine("Tshirt39:{0} Unit(s)",icount);
Console.ReadLine();

我想要ouput&#34; Tshirt&#34;是:2 :( enter image description here

1 个答案:

答案 0 :(得分:1)

尝试使用正则表达式(提取商品)和 Linq (将商品组合成正确的代表):

  String source = "Tshirt39Tshirt39Tshirt15Jean39Jean52Jean52Jean52";

  var result = Regex
    .Matches(source, "(?<name>[A-Z][a-z]+)(?<size>[0-9]+)")
    .OfType<Match>()
    .Select(match => match.Value)
    .GroupBy(value => value)
    .Select(chunk => String.Format("{0}:{1} Unit(s)", 
       chunk.Key, chunk.Count()));

  String report = String.Join(Environment.NewLine, result);

测试:

  // Tshirt39:2 Unit(s)
  // Tshirt15:1 Unit(s)
  // Jean39:1 Unit(s)
  // Jean52:3 Unit(s)
  Console.Write(report);

如果您想要第二种类型表示:

  var result = Regex
    .Matches(source, "(?<name>[A-Z][a-z]+)(?<size>[0-9]+)") // same regex
    .OfType<Match>()
    .Select(match => new {
      name = match.Groups["name"].Value,
      size = int.Parse(match.Groups["size"].Value),
    })
    .GroupBy(value => value.name)
    .Select(chunk => String.Format("{0}: {1}", 
       chunk.Key, String.Join(" + ", chunk.Select(item => item.size))));

  String report = String.Join(Environment.NewLine, result);

测试:

  // Tshirt: 39 + 39 + 15
  // Jean: 39 + 52 + 52 + 52
  Console.Write(report);