如何检查一个整数是否包含c#中的某个数字
How to check if an integer includes a certain number in c#
有没有一种方法可以检查整数是否包含 C# 中的特定数字?
For example:
I want to check for 7. When I enter 17, the code will return 1. When I enter 28, the code will return 0.
谢谢
int number = 17;
int digit = 7;
bool result = number.ToString().Contains(digit.ToString());
将其转换为字符串,然后使用String.Contains
:
int i = 17;
int j = 28
int k = 7;
bool a = i.ToString().Contains(k.ToString());
bool b = j.ToString().Contains(k.ToString());
我们可以在不将数字转换为字符串的情况下使用 while 循环找到它。
This way is not recommended. But it will help some people who are new
to coding.
假设你的号码是“number”,“digit”是你要查询的某个号码包含在“number”中,本例中是7,号码是17,
public bool includesInteger(int number, int digit)
{
while(number > 0)
{
if (number % 10 == digit) return true;
number /= 10;
}
return false;
}
道理很简单。快乐编码
有没有一种方法可以检查整数是否包含 C# 中的特定数字?
For example:
I want to check for 7. When I enter 17, the code will return 1. When I enter 28, the code will return 0.
谢谢
int number = 17;
int digit = 7;
bool result = number.ToString().Contains(digit.ToString());
将其转换为字符串,然后使用String.Contains
:
int i = 17;
int j = 28
int k = 7;
bool a = i.ToString().Contains(k.ToString());
bool b = j.ToString().Contains(k.ToString());
我们可以在不将数字转换为字符串的情况下使用 while 循环找到它。
This way is not recommended. But it will help some people who are new to coding.
假设你的号码是“number”,“digit”是你要查询的某个号码包含在“number”中,本例中是7,号码是17,
public bool includesInteger(int number, int digit)
{
while(number > 0)
{
if (number % 10 == digit) return true;
number /= 10;
}
return false;
}
道理很简单。快乐编码