简体   繁体   中英

How to check if a number exists in a specified digit of an integer ( C# )

I want to generally verify if a number/character exists within a specified index of an int value.

Here is pseudocode of what I want

        if (octet[1].Exists){
          return true;
        } else {
          return false;
        }

        // receiving int octet = 103 will return true.
        // receiving int octet = 7 will return false.

Is there a function that already does this, or do you have to make one on your own?

Convert to a string then check the length?

var str = octet.ToString();
return str.Length >= 1;

I don't know a function like this, but you can write your own. In instance:

var func = (int octet, int index) => (octet / (int)(Math.Pow(10, index)) != 0);

I would suggest using a System.Linq binding for this. Here is an example:

octet.ToString().Contains(n);

Where n is the digit you're looking for in string or char form. Hope this helps!

Just parse the int to a string and check if the number you are looking is equal to expected position.

  var number = 12345;
            if(number.ToString().IndexOf('2') == 1)//check if the value 2 is on the second position of the array
            {
                Console.WriteLine("yes");
            }

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