i have a code capturing ODD EVEN numbers in a textbox , is there a betterway of doing this in minimal code? or maybe much faster performance? thnks -john :)
string givenamnt = Convert.ToString(txtamount.Amount.Replace(".", ""));
int glength = givenamnt.Length;
var regex = new Regex("[1]|[3]|[5]|[7]|[9]");
string odd = null;
string even = null;
for (int i = 0; i < glength; i++)
{
var x1 = givenamnt.Substring(i, 1);
var isOdd = regex.IsMatch(x1);
if (isOdd)
{
odd += x1;
txtodd1.Text = odd;
}
else
{
even += x1;
txteven1.Text = even;
}
}
Yes.You can use Modulus
if( Convert.ToInt32(x1) % 2 == 0 ) //even
else // odd
Definitely not an elegant solution, but to get the actual even and odd digits you can use this:
string str = "230sd85"; // sample string with invalid input for numbers
var odd = str
.Where(x => char.IsDigit(x)
&& Convert.ToInt32(x) % 2 != 0);
var even = str
.Where(x => char.IsDigit(x)
&& Convert.ToInt32(x) % 2 == 0);
string oddNums = string.Join("", odd); // 35 - the numbers 3 and 5, not 35
string evenNums = string.Join("", even); // 208 - the numbers 2, 0 and 8
Is this what you meant by digits?
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.