开发者

Help checking if number value in string is odd C#

I have the method GetOption(5) that returns the value 5K23 and I need to get the last two characters of the string the thing is the value is a string value, so I would need to use Substring I have tried doing:

if( Convert.ToInt32(GetOption(5).Substr开发者_StackOverflow社区ing(GetOption(5).Length-2, 2) % 2 == 1) )

I can't seem to get it right, can anyone help me out.

Thanks


You don't really need last two digits to determine whether number is odd

var option = GetOption(5);
var isOdd = int.Parse(option[option.Length - 1].ToString()) % 2 == 1;


var t = "5K23";
var regex = new Regex(@"\d{2}$");
var match = regex.Match(t);
if (match.Success)
{
    var extracted = match.Value;
    // Do more stuff
}


I like @Lukáš' answer (+1) but the reason your code doesn't work is...

Convert.ToInt32
(
    GetOption(5).Substring
    (
        GetOption(5).Length-2, 2
    ) % 2 == 1
)

Incorrect paren grouping. You're passing <long thing> % 2 == 1 to Convert.ToInt32().

Try to keep lines short and readable.

var s = GetOption(5);
if(Convert.ToInt32(s.Substring(s.Length-2, 2)) % 2 == 1)
{
    // do stuff
}


    int x;
    string option = GetOption(5);
    if (Int32.TryParse(option.Substring(option.Length - 2), out x) && x % 2 == 1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜