-2

I have an input string like this:

Tshirt39Tshirt39Tshirt15Jean39Jean52Jean52Jean52

And then I want to have an output:

Tshirt39:2 Unit(s)
Tshirt15:1 Unit(s)
Jean39:1 Unit(s)
Jean52:3 Unit(s)

Or

Tshirt:15+39+39 Jean:39+52+52+52"

This my code:

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

I want result of ouput "Tshirt" is: 2 :( enter image description here

DIF
  • 2,470
  • 6
  • 35
  • 49
  • 1
    Please attempt to solve the problem yourself, and post the code here so we can help you. If you are not sure where to start, I suggest looking into the String.Contains() method: https://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx and the String.Split() method: https://msdn.microsoft.com/en-us/library/ms228388.aspx – Matt Dalzell Jun 21 '16 at 14:28
  • You can't solve the problem but at least you can format the code and post a proper question right? – Rahul Jun 21 '16 at 14:31
  • Thanks man, i tried use loop For and String.Contains() method but it just show "Tshirt39" 1 time :( not 2 times. – Hung Nguyen Jun 21 '16 at 14:51
  • 1
    Possible duplicate of [How would you count occurrences of a string within a string?](http://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-within-a-string) – DIF Jun 22 '16 at 07:51
  • Thanks man, I'm studying REGEX :3 @DIF – Hung Nguyen Jun 23 '16 at 14:40

1 Answers1

1

Try using regular expressions (to extract goods) and Linq (to combine the goods into proper representation):

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

Test:

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

If you want second type representation:

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

Test:

  // Tshirt: 39 + 39 + 15
  // Jean: 39 + 52 + 52 + 52
  Console.Write(report);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215