2016-06-21 36 views
-2

我有一个输入串是这样的:C#。如何在较大的字符串中查找小字符串?

Tshirt39Tshirt39Tshirt15Jean39Jean52Jean52Jean52

然后,我想有一个输出:

Tshirt39:2单位(一个或多个)
Tshirt15:1单位
Jean39:1 Unit(s)
Jean52:3 Unit(s)

或者

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(); 

我想结果输出“T恤”是:2 :( enter image description here

+1

请尝试自己解决问题,并在此处发布代码,以便我们可以为您提供帮助。如果你不确定从哪里开始,我建议查看一下String.Contains()方法:https://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx和String .Split()方法:https://msdn.microsoft.com/en-us/library/ms228388.aspx –

+0

你不能解决问题,但至少你可以格式化代码并发布适当的问题吗? – Rahul

+0

谢谢你,我试过使用循环For和String.Contains()方法,但它只是显示“Tshirt39”1次:(不是2次) –

回答

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); 
+0

谢谢你支持男人:D看它看起来不像C#语言(或使用SQL服务器):(或者我的水平很低 –

+0

@Hung Nguyen:* Linq *是C#的典型特征,恕我直言,值得研究。 –

+0

WOW。got谢谢你这么多人! –

相关问题