Home > Blockchain >  Build a string with variables, cutting null variables off
Build a string with variables, cutting null variables off

Time:02-04

I want to write a string with some variables but when the specific value isn't necessary, it can be cut off.

e.g.:

int apples = 5;
int oranges = 8
int bananas = 0;

string.Format("I got {0} apples, {1} oranges, {2} bananas.", apples, oranges, bananas)

Output: I got 5 apples, 8 oranges, 0 bananas.

I want to cut off ", 0 bananas", as they aren't necessary to show here. My only solution would be if-states for every fruit... Imagine I can have 10 fruits...

if (bananas == 0)
{
    string.Format("I got {0} apples, {1} oranges.", apples, oranges)
}

My next problem is that I can have more than one fruit to be 0. This will be an endless if-state within an if-state... Is there any solution to solve this within one line?

I don't even know what I can do here. I just know the ways of inverting variables with the use of operator, using string.Format() or using $ before the actual string.

Many thanks! Netroshin

CodePudding user response:

You don't have to have a bunch of different if statements for every possibly combination, you can just build the string with a single if for each fruit. This can be simplified using the ?: ternary operator, which has a condition on the left side of the ?, followed by a result if the condition is true, then a : followed by a result if the condition is false. Since we want a comma at the end of each string, I added a TrimEnd(',') to remove the last one:

string result = "I got"  
    ((apples > 0 ? $" {apples} apples," : "")  
    (oranges > 0 ? $" {oranges} oranges," : "")  
    (bananas > 0 ? $" {bananas} bananas" : "")).TrimEnd(',');

You also might consider putting your data into a better structure. Instead of storing them as int types, you could create your own type that has both a string name and an int quantity. In this way, you can filter a list of these items on the quantity (remove all where quantity == 0), and then print them out using the Name property.

For example:

public class Fruit
{
    public string Name { get; set; }
    public int Quantity { get; set; }
}

public class Program
{
    // Create a list of fruits
    List<Fruit> fruits = new List<Fruit>();
    fruits.Add(new Fruit { Name = "Apples", Quantity = 5 });
    fruits.Add(new Fruit { Name = "Oranges", Quantity = 8 });
    fruits.Add(new Fruit { Name = "Bananas", Quantity = 0 });

    string result = "I got "   string.Join(", ", fruits
        .Where(fruit => fruit.Quantity > 0)
        .Select(fruit => $"{fruit.Quantity} {fruit.Name}"));

    Console.WriteLine(result);
    Console.ReadKey();
}

CodePudding user response:

How about

 StringBuilder sb;
  sb.Append("I got ");
 if(oranges > 0){
    sb.Append(String.Format("{0} oranges,"));
 }
 if(apples > 0){
    sb.Append(String.Format("{0} apples,"));
 }
 ...
 var res = sb.ToString();
  • Related