2

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).Substring(GetOption(5).Length-2, 2) % 2 == 1) )

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

Thanks

Sandeep Bansal
  • 6,280
  • 17
  • 84
  • 126
  • 1
    Wouldn't it be better to check it using a regular expression? Something like `^.*[0-9][13579]$` – khachik Jun 24 '11 at 18:03
  • 2
    @khachik I dunno about "better", but I like it. Could also just do `[13579]$`, to "align with the title". –  Jun 24 '11 at 18:04
  • @pst, "better" here means "faster" and putting less burden to the GC. – khachik Jun 24 '11 at 18:05
  • @khachik I usually measure "better" by "ease to understand and maintain", in which case I agree that the Regex is more clear than the code in the post, even if there are other alternatives ;-) I don't even consider the other "better" until after I've dug out the profiling... but then I don't write XNA games for the XBox or do any mobile development. –  Jun 24 '11 at 18:11

4 Answers4

7

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;
Lukáš Novotný
  • 9,012
  • 3
  • 38
  • 46
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
}
ba__friend
  • 5,783
  • 2
  • 27
  • 20
  • 1
    I find the regular expression here *much* more readable and intuitive than the Substring approach -- although I would just use [`Regex.Match`](http://msdn.microsoft.com/en-us/library/0z2heewz.aspx) here. That Perlesque semi-quote isn't terribly justified here, IMOHO ;-) –  Jun 24 '11 at 18:06
1

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
}
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    The indexes passed to SubString in the OP are fine. You want to start at len-2 for 2 characters. starting for len-2 and copying len characters is incorrect and will throw an ArgumentOutOfRangeException. – mletterle Jun 24 '11 at 18:14
  • You're right, I assumed that `Substring()` with 2 int arguments worked the same in C# as in Java (I'm a Java guy). Clearly this was incorrect! Edited accordingly. Thank you. – Matt Ball Jun 24 '11 at 18:34
0
    int x;
    string option = GetOption(5);
    if (Int32.TryParse(option.Substring(option.Length - 2), out x) && x % 2 == 1)
mletterle
  • 3,968
  • 1
  • 24
  • 24