简体   繁体   中英

Find specific digit in number

I need to find specific digit in numbers. For example I have the following numbers

156, 14, 28,34

And I need to find out, how many numbers have digit 4 .

All you need is a simple Linq :

string source = "156, 14, 28,34";

// 2 since there're two numbers - 14, 34 which contain 4 
int result = source
  .Split(',')
  .Count(number => number.Contains('4'));

If you're given an array int[] :

int[] source = new[] {156, 14, 28, 34};

// 2 since there're two numbers - 14, 34 which contain 4 
int result = source
  .Count(number => number.ToString().Contains('4'));

You can make a try with this:

List<int> inputNumbers = new List<int>(){156, 14, 28,34};
int givenNumber = 4;
var numbers = inputNumbers.Where(x=> 
                                 x.ToString().Contains(givenNumber.ToString())
                                ).ToList();

Output will be 14 and 34 , Here is a working Example for you

var lst = new[] {156, 14, 28,34};
var contains4 = lst.Where(c=>c.ToString().Contains("4"));

Output:

14 34

Strings are slow.

This method will return true if number contains digit .

private static bool ContainsDigit(int number, int digit)
{
    if (number == 0 && digit == 0)
    {
        return true;
    }

    for (var value = number; value > 0; value /= 10)
    {
        if (value % 10 == digit)
        {
            return true;
        }
    }

    return false;
}

is used like this

var values = new []{156, 14, 28, 34, 0};

foreach (var value in values)
{
    if (ContainsDigit(value, 4))
    {
        Console.Write($"{value} ");
    }
}

Console.WriteLine();

which prints the result

14 34

Your specific use-case will dictate which works best for you

try this

int[] a={156, 14, 28,34};
int count = 0;
foreach (int t in a)
{
  if (t.ToString().Contains('4') == true)
  {
    Console.WriteLine(t);
  }
}

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