Tikeb Tikeb - 2 months ago 34
C# Question

c# UK postcode splitting

I need a way to split a UK postcode from user entry. This means the postocode could be nicely formatted full code like so "AB1 1BA" or it could be anything you could imagine. I've seen some regex to check the format of the postcode but it's knowing where to split it if I'm given something like "AB111AD" etc..
This is to return the first part of the postcode, in the example above would be "AB11". Any thoughts?
Thanks..

Answer

I'm not sure how UK Post Codes work, so is the last part considered the last 3 characters with the first part being everything before?

If it is, something like this should work, assuming you've already handled appropriate validation: (Edited thanks to Jon Skeets commment)

string postCode = "AB111AD".Replace(" ", "");
string firstPart = postCode.Substring(0, postCode.Length - 3);

That will return the Post Code minus the last 3 characters.