简体   繁体   中英

How to get a specific part of a string and use it for a calculation

So I have to make a vending machine where I have a listbox (lstBeverage) to put all the drinks in. The thing is that it must be in a string format (for example: cola of 33cl - 1,20 euro, fanta - 2,00 euro is what is in the listbox).

There is also a button btnAdd that whenever I click on it, it has to come into a label lblBeverage where it shows the string format from the listbox (for example cola of 33cl - 1,20 euro). But there is also another label lblToPay that must only show the price of each drink. So only the 1,20 euro - part of the sentence. Is there any way how I can do that?

Final thing is that I need the amount from lblToPay and reduce it with buttons that indicates coins (btn2euro, btn1euro,..). To pay the amount of the drink.. I'm kinda stuck on how to do this as well.

Sorry if this ever sound complex. I'm a beginner programmer and stuck in this part of my exercise. If more details are required I can show exacly what I mean.

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        DoStartup();
    }

    
    void DoStartup()
    {
        lstBeverage.Items.Add($"Cola 33cl - ${cola33.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Cola light 33cl - €{colaLight33.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Cola 50cl - €{cola50.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Cola light 50cl - €{colaLight50.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Icetea - €{iceTea.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Icetea light 33cl - €{iceTeaLight.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Spa rood 50cl - €{spaRood.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Spa blauw 50cl - €{spaBlauw.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Fristi 50cl - €{fristi.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Riva cola - €{riva.ToString("#,##0.00")}");
        lstBeverage.Items.Add($"Red Bull Super 50cl - €{redBull.ToString("#,##0.00")}");

        grpStep2.IsEnabled = false;
        grpStep3A.IsEnabled = false;
        grpStep3B.IsEnabled = false;


    }

    decimal cola33 = 1.2M;
    decimal colaLight33 = 1.2M;
    decimal cola50 = 2.0M;
    decimal colaLight50 = 2.0M;
    decimal iceTea = 1.2M;
    decimal iceTeaLight = 1.2M;
    decimal spaRood = 1.2M;
    decimal spaBlauw = 1.0M;
    decimal fristi = 1.6M;
    decimal riva = 0.9M;
    decimal redBull = 2.3M;

    string substr;

    private void btnConfirmBeverage_Click(object sender, RoutedEventArgs e)
    {
        
        if (lstBeverage.SelectedItem != null)
        {
            lblChosenBeverage.Content = lstBeverage.SelectedItem;
            string value = lblChosenBeverage.Content.ToString();
            string substr = "€" + value[^4..];
            lblToPay.Content = substr;


            if (lblChosenBeverage.Content.ToString() == "")
            {
                lstBeverage.IsEnabled = true;
                btnConfirmBeverage.IsEnabled = true;
                grpStep2.IsEnabled = false;
            }
            else
            {
                lstBeverage.IsEnabled = false;
                btnConfirmBeverage.IsEnabled = false;
                grpStep2.IsEnabled = true;
            }

        }
        
        

    }

String-based solution

To get the price from the string, you could use regular expressions:

    var foo = $"Cola 33cl - {(1.23654M).ToString("#,##0.00")}";
        
    var price = Regex.Match(foo, @"(\d+[,.]\d+)").Value;
        
    Console.WriteLine(price); // prints 1.24

For this to work, you need using System.Text.RegularExpressions; at the top of your file.

Keep in mind that this solution returns only the first occurence of a number in a string. If there are multiple prices in your string, only the first is returned.

WARNING: This is not a good practice and i strongly reccomend to use the class-bases solution below.

Class-Bases Solution

I would recommend to create a small class that holds the needed data for a beverage.

Something like this:

public class Beverage {
    public string Name { get; set; }
    public string ContentSize { get; set; }
    public double Price { get; set; }
}

Then change your lstBeverage to hold objects of type Beverage instead of type string and initialize it like so:

lstBeverage.Items.Add(new Beverage
{
    Name = "Cola",
    ContentSize = "33cl",
    Price = 1.2M
});

...

Now, instead of using substring, you can use (lstBeverage.SelectedItem as Beverage).Price to get the price.

First I suggest you write a class which deals with your beverages. Since this class is just for formatting string and stuff, this class does not belong to the business model of your application, but rather the viewmodel (if you have such a distinction).

public class Beverage
{
    public decimal Price;
    public string Name;

    public Beverage(string name, decimal price)
    {
        Price = price;
        Name = name;
    }

    public string FullDisplay => $"{Name} - {DisplayPrice}";

    public string DisplayPrice => $"€{Price:#,##0.00}";

    public override string ToString()
    {
        return "ToString() was called";
    }
}

Your window might use data binding to itself using

DataContext="{Binding RelativeSource={RelativeSource Self}}"

and the Listbox set up like this:

<StackPanel>
    <ListBox x:Name="lstBeverage" 
             ItemsSource="{Binding Beverages}" 
             DisplayMemberPath="FullDisplay"
             SelectionChanged="LstBeverage_OnSelectionChanged"
             SelectionMode="Single">
    </ListBox>
    <Label x:Name="lblPrice" Content="Price will appear here">
    </Label>
</StackPanel>

The code behind file has the Beverages property for the item source of the ListBox as well as a bit of code handling the selected item:

public partial class MainWindow : Window
{
    public ICollection<Beverage> Beverages { get; set; } = new ObservableCollection<Beverage>();
    public MainWindow()
    {
        InitializeComponent();

        Beverages.Add(new Beverage("Cola 33cl", 1.2M));
        Beverages.Add(new Beverage("Cola light 33cl", 1.2M));
        Beverages.Add(new Beverage("Cola 50cl ", 2.0M));
    }

    private void LstBeverage_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (lstBeverage.SelectedItems.Count == 0) return;
        Beverage selected = (Beverage) lstBeverage.SelectedItems[0];
        lblPrice.Content = selected.DisplayPrice;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM