Santosh Santosh - 1 year ago 81
C# Question

Check for specific digits in a number

I want to check for certain digits in a number and based on the result it should print a message.

Digits to check: 7 and 9
Output: if 7,Print S and if 9, Print N(Order is important) and no 7 or 9,Print input number.

for ex:

input number:75 Output: S(Contains 7)

input number:96 Output: N(Contains 9)

input number:79 Output: SN

input number:97 Output: NS

input number:67849 Output: SN

input number:59587 Output: NS

input number:873579 Output: SSN

input number:135 Output: 135

I tried the following approach

string output = string.Empty;
int n = 0;
while(number > 0)
n = number % 10;
number = number / 10;
if(n == 7)
output += "S";
if(n == 9)
output += "N";


return string.IsNullOrEmpty(output) ? number.ToString() : output;

But this is working only if it contains one digit(for ex: works for 17,91)

It's not working if it has multiple numbers(for ex:769,957)

How to achieve this(Order is important).

Thanks in advance

Answer Source

I would convert to string first, therefore no math calculation is required and it will preserve the order.

string numberStr = number.ToString();
string result = null; // no need to use StringBuilder, because size won't be big
foreach (char c in numberStr)
    switch (c)
        case '7':
            result +='S';
        case '9':
            result +='N';
return string.IsNullOrEmpty(result) ? numberStr : result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download