Reputation: 153
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
.
Upvotes: 1
Views: 318
Reputation: 5480
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
Upvotes: 1
Reputation: 186793
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'));
Upvotes: 2
Reputation: 1192
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);
}
}
Upvotes: 0
Reputation: 9679
var lst = new[] {156, 14, 28,34};
var contains4 = lst.Where(c=>c.ToString().Contains("4"));
Output:
14 34
Upvotes: 1
Reputation: 29026
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
Upvotes: 1