简体   繁体   English

如何检查字符串变量类型

[英]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#.这是在 Visual Studio 中完成的,语言是 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.而且我还想检查它们是否是 typinh 一个字母。 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.但是,如果他们都输入字母(即至少 2 个字母),那么我想继续使用下一个方法,在我的例子中是 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.我尝试了很多东西,if 语句,switch 语句,但我似乎需要调用 boolean 变量。 I am not sure how to do it.我不知道该怎么做。 I am quite new to programming.我对编程很陌生。

Thanks for all the help: :D感谢所有帮助::D

Using foreach使用 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:您可以解析字符串的字符并使用char.IsLetterchar.IsNumberchar.IsDigit像这样,有或没有扩展方法:

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# C# 中 Char.IsDigit() 和 Char.IsNumber() 的区别

Using Linq使用 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. Linq 可能比循环慢,也可能比循环快,具体取决于对性质、复杂性和数据量进行的处理。 But Linq provides simple, clean, small, maintainable, robust, and magical code once learned.但是 Linq 提供了简单、干净、小型、可维护、健壮和一旦学会的神奇代码。

For vs. Linq - Performance vs. Future 对于与 Linq - 性能与未来

Is a LINQ statement faster than a 'foreach' loop? LINQ 语句是否比“foreach”循环快?

Is the LINQ version faster than the foreach one? LINQ版本比foreach快吗?

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:事实上,我们可以写来检查 integer 还是双精度:

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:如果需要,您还可以使用 char position:

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.所以:正如你所看到的,我要求用户至少投入到 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.但我只检查它们是否以 0 回答,然后我将它们发送回方法的开头。 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.在至少输入两次输入后,我问他们是否完成了,并使用 switch 语句我只允许他们回答 ja/nej,这是瑞典语中的是和否。 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.如果他们回答是,我将它们发送到我还没有查看的比较方法,因为这里的想法是打印包含整数的列表的最小值和最大值,并且与这些整数在整数列表中占据的 position 相同我还想在字符串列表中打印出相同 position 上的内容以显示元素的名称。

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.但是,是的,第一个问题是在 Ingridiens 和 NastaIngridiens 方法中输入一个 ingridient 名称时,只能允许他们输入一个字母和至少两个字母。

using System;使用系统; using System.Collections.Generic;使用 System.Collections.Generic;

namespace Inlamning22命名空间 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 ");
    }

    }
}
    

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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