views:

31

answers:

1

I have an IP address which I want to grab the last chunk of as an integer. So from "192.168.1.150" I'd get 150.

This is the code I'd concocted (I'm using C++/CLI), but somehow it feels rather clunky:

String^ ipString = "192.168.1.150";
int lastDot = ipString->LastIndexOf('.');
int lastSection = int::Parse(ipString->Substring(lastDot, ipString->Length-lastDot));

Is there a simpler way of doing this?

+1  A: 

Does that code really work? Shouldn't it read?:

int lastDot = ipString->LastIndexOf('.') + 1;

You don't have to specify the lengt to Substring if you want all that's left in the string, so you can shorten it to:

String^ ipString = "192.168.1.150";  
int lastSection = int::Parse(ipString->Substring(ipString->LastIndexOf('.') + 1) ; 

Not much of an improvement though, but I doubt you can do much better.

danbystrom
Well done; you've spotted my obvious mistake :-)
Jon Cage
Was it just a test? ;-)
danbystrom
You passed... and it's nice to know I've not missed anything obvious :-)
Jon Cage
Of course, doing this is certainly a bug; what about the netmask? If the network isn't a /24, that octet isn't unique.
Andrew McGregor
I don't need a unique octet, just those last digits. I can't go into the specifics, but this is perfectly valid for my application.
Jon Cage