简体   繁体   中英

How to check a string variable type

I am programming a thing where I am asking a user to type in several ingridients, how much they want of it and what the kg/ml/liter/etc price is. So that I add all the cost values(after multiplying the cost per unit times the measure they want) later display for them the most cheap and expensive ones. This is done in Visual Studio and the language is in C#. So I am typing this:

        static void Ingridiens()
        {
            string ingridiensen;
            Console.Write("Vad för ingridiIngridiensens behöver du?\nIngridiens: ");
            ingridiensen = Console.ReadLine();
            listaformat.Add(ingridiensen);
            PrisPerEnhetEtt(prisetPerEnhet);
        }

Ignore the variable names since they are in swedish. What I want help in is to check whether the input of the user is letters or something else. If they are not letters like numbers or any other special characters I want to return an error. And I also want to check if they are typinh one letter or not. It is one letter I still wanna return an error. But if they both type in letters(ie at least 2 letters) than I want to move on to the next method which in my case is PrisPerEnhetEtt.

I am finding it hard to fix this. I tried a lot of stuff, if statements, switch statements but i seems i need to invoke boolean variables. I am not sure how to do it. I am quite new to programming.

Thanks for all the help: :D

Using foreach

You can parse the chars of the string and use char.IsLetter and char.IsNumber orchar.IsDigit like that with or without extension methods:

static public class StringHelper
{

  static public bool IsText(this string input)
  {
    foreach ( char c in input )
      if ( c != ' ' && !char.IsLetter(c) )
        return false;
    return true;
  }

  static public bool IsNumber(this string input)
  {
    foreach ( char c in input )
      if ( !char.IsNumber(c) )
        return false;
    return true;
  }

}

Difference between Char.IsDigit() and Char.IsNumber() in C#

Using Linq

using System.Linq;

static public bool IsText(this string input)
{
  return input.All(c => c == ' ' || char.IsLetter(c));
}

static public bool IsNumber(this string input)
{
  return input.All(c => char.IsNumber(c));
}

Or:

static public bool IsText(this string input)
  => input.All(c => c == ' ' || char.IsLetter(c));

static public bool IsNumber(this string input)
  => input.All(char.IsNumber);

Linq can be as slow as it is faster than loops depending on the processing done on the nature and the complexity and the amount of data. But Linq provides simple, clean, small, maintainable, robust, and magical code once learned.

For vs. Linq - Performance vs. Future

Is a LINQ statement faster than a 'foreach' loop?

Is the LINQ version faster than the foreach one?

Usage

string ingridiensen;
Console.Write("Vad för ingridiIngridiensens behöver du?\nIngridiens: ");
ingridiensen = Console.ReadLine();

Console.WriteLine(ingridiensen.IsNumber());
Console.WriteLine(ingridiensen.IsText());

Remark

In fact we can write to check if integer or double:

return int.TryParse(input, out var _);

return double.TryParse(input, out var _);

Advanced conditions

You can adapt the test conditions and create as many methods to match your needs: lower or upper case, space or no space allowed, point, special chars, integers, decimals, and so on:

static public bool IsWhatYouNeed(this string input)
{
  foreach ( char c in input )
    if ( !match(c) )
      return false;
  return true;
  void bool match(char c)
  {
    ...
  }
}

You can also use the char position if needed:

static public bool IsWhatYouNeed(this string input)
{
  for ( int index = 0; index < input.Length; index++ )
    if ( !match(input[index], index) )
      return false;
  return true;
  void bool match(char c, int pos)
  {
    ...
  }
}

The code above is lousy but written to give you the idea if needed.

I think I am getting overwhelmed by the answer however I appreciate your help. I think it is better if I post my entire written code you get the point:

So: As you can see I am asking the user to put in at least to ingridiences. And for each ingridience I have created two more methods where I first ask what is the unit price of it and then another method for how many units they need of it. But I am only checking if they are answer with a 0 then I send them back to the beginning of the method. If they add something else then it is being added into a list. After at least two typed ingridiences I ask them if they are done and with an switch statement I only allow them to answer ja/nej which is swedish for yes and no. If they answer with a no they will be sent to first method to once again to the asking process for a third ingridient. If they answer yes i send them to the Compare method which I haven't look at it yet because the idea there is to print the min and max of the list containing the integers and at the same position as those integers occupy in the integers list i want also to print out what's on the same position in the string list to display the name of the ingridient.

But yes the first problem is to be able to only allow them to type in onyl letters and atleast two letters when entering an ingridient name in the methods Ingridiens and NastaIngridiens.

using System; using System.Collections.Generic;

namespace Inlamning22

{

class Program

{


    static List<float> kostnader = new List<float>();
    static List<string> listaformat = new List<string>();
    static float prisetPerEnhet;
    static float prisetPerEnhetNasta;

    static void Main(string[] args)
    {
        Ingridiens();

        NastaIngridiens();

        AreYouDone();
    }


    static void Ingridiens()
    {
        string ingridiensen;
        Console.Write("Vad för ingridiIngridiensens behöver du?\nIngridiens: ");
        ingridiensen = Console.ReadLine();
        listaformat.Add(ingridiensen);
        PrisPerEnhetEtt(prisetPerEnhet);
    }
    static void PrisPerEnhetEtt(float prisetPerEnhet)
    {
        Console.WriteLine("Vad kostar den/det per enhet? ");

        prisetPerEnhet = float.Parse(Console.ReadLine());
        float kost = prisetPerEnhet;
        switch (kost)
        {
            case 0: PrisPerEnhetEtt(prisetPerEnhet); break;
            default: KostnadEtt(kost); break;
        }
    }
    static void KostnadEtt(float kost)
    {
        float totalt;
        Console.WriteLine("Hur mycket/många enheter ska du ha av det? ");
        float onskadMangd = float.Parse(Console.ReadLine());
        switch (onskadMangd)
        {
            case 0: KostnadEtt(kost); break;
            default: totalt = kost * onskadMangd; kostnader.Add(totalt); break;
        }
    }

    static void NastaIngridiens()
    {
        Console.Write("Vad för ingridiens behöver du?\nIngridiens: ");
        string ingridienser = Console.ReadLine();
        listaformat.Add(ingridienser);
        PrisPerEnhetTva(prisetPerEnhetNasta);
    }
    static void PrisPerEnhetTva(float prisetPerEnhetNasta)
    {
        Console.WriteLine("Vad kostar den/det per enhet? ");
        prisetPerEnhetNasta = float.Parse(Console.ReadLine());
        float kostTva = prisetPerEnhet;
        switch (kostTva)
        {
            case 0: PrisPerEnhetTva(prisetPerEnhetNasta); break;
            default: KostnadTva(kostTva); break;
        }
    }

    static void KostnadTva(float kostTva)
    {
        float totaltTva;
        Console.WriteLine("Hur mycket/många enheter ska du ha av det? ");
        float onskadMangd = float.Parse(Console.ReadLine());
        totaltTva = kostTva * onskadMangd;
    
        switch (onskadMangd)
        {
            case 0: KostnadTva(kostTva); break;
            default: totaltTva = kostTva * onskadMangd; kostnader.Add(totaltTva); break;
        }
    }

    static void AreYouDone()
    {
        Console.WriteLine("Är du klar?");
        string svar = Console.ReadLine();
        switch (svar)
        {
            case "nej": Ingridiens(); AreYouDone(); break;
            case "NEJ": Ingridiens(); AreYouDone(); break;
            case "Nej": Ingridiens(); AreYouDone(); break;
            case "nEj": Ingridiens(); AreYouDone(); break;
            case "neJ": Ingridiens(); AreYouDone(); break;
            case "NeJ": Ingridiens(); AreYouDone(); break;
            case "nEJ": Ingridiens(); AreYouDone(); break;
            case "NEj": Ingridiens(); AreYouDone(); break;
            case "ja": Compare(); break;
            case "JA": Compare(); break;
            case "jA": Compare(); break;
            case "Ja": Compare(); break;
            default: Console.Write("Svara med ja/nej."); AreYouDone(); break;
        }


    static void Compare()
    {
       Console.WriteLine("Den dyraste ingridiensen är" + " och kostar.\nDen billigaste ingridiensen är " + " och kostar ");
    }

    }
}
    

}

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