Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Exercise: Regular Expressions
- Problems for exercise and homework for the "C# Fundamentals" course @ SoftUni
- You can check your solutions in Judge
- 01. Furniture
- Write a program to calculate the total cost of different types of furniture. You will be given some lines of input until you receive the line "Purchase". For the line to be valid it should be in the following format:
- ">>{furniture name}<<{price}!{quantity}"
- The price can be floating point number or whole number. Store the names of the furniture and the total price. At the end print the each bought furniture on separate line in the format:
- "Bought furniture:
- {1st name}
- {2nd name}
- …"
- And on the last line print the following: "Total money spend: {spend money}" formatted to the second decimal point.
- Examples
- Input Output Comment
- >>Sofa<<312.23!3 Bought furniture: Only the Sofa and the TV are valid, for each of them we
- >>TV<<300!5 Sofa multiply the price by the quantity and print the result
- >Invalid<<!5 TV
- Purchase Total money spend: 2436.69
- >table<!3 Bought furniture:
- Purchase Total money spend: 0.00
- using System;
- using System.Text.RegularExpressions;
- using System.Collections.Generic;
- public class Program
- {
- public static void Main()
- {
- var pattern = @">>(?<Furniture>[A-Z\sa-z]*)<<(?<Price>\d+(.\d+)?)!(?<Quantity>\d+)";
- var boughtFurniture = "";
- var totalSum = 0.0;
- var listFurniture = new List<string>();
- while ((boughtFurniture = Console.ReadLine()) != "Purchase")
- {
- var matchFurniture = Regex.Matches(boughtFurniture, pattern);
- if (matchFurniture.Count == 0)//Може и без форийчване чрез if (matchFurniture.Success), който връща True или False
- { //{var nameFurniture = matchFurniture.Groups[2].Value;
- continue; //var price = double.Parse(matchFurniture.Groups[3].Value);
- } //var quantity = int.Parse(matchFurniture.Groups[4].Value);
- foreach (Match type in matchFurniture) //...........
- { //else{continue;} //група 1 = (.\d+)
- var nameFurniture = type.Groups[2/*"Furniture"*/].Value; //група 2 = (?<Furniture>[A-Z\sa-z]*)
- listFurniture.Add(furniture);
- var price = type.Groups[3/*"Price"*/].Value; //група 3 = (?<Price>\d+(.\d+)?)
- var quantity = type.Groups[4/*"Quantity"*/].Value; //група 4 = (?<Quantity>\d+)
- totalSum += double.Parse(price) * double.Parse(quantity);
- }
- }
- if (listFurniture.Count > 0)
- {
- Console.WriteLine($"Bought furniture:\n{string.Join("\n", listFurniture)}\nTotal money spend: {totalSum:F2}");
- }
- else
- {
- Console.WriteLine($"Bought furniture:\nTotal money spend: {totalSum:F2}");
- }
- //Console.WriteLine($"Bought furniture:"); Друг вариант на завършек.
- //if (listFurniture.Count > 0)
- //{
- //Console.WriteLine($"{string.Join(Environment.NewLine, listFurniture)}");
- //}
- //Console.WriteLine($"Total money spend: {totalSum:F2}");
- }
- }
Add Comment
Please, Sign In to add comment