Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# UK postcode splitting

Tags:

string

c#

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..

like image 348
Tikeb Avatar asked Jul 23 '09 14:07

Tikeb


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

I've written something similar in the past. I think you can just split before the last digit. (e.g. remove all spaces, find the last digit and then insert a space before it):

static readonly char[] Digits = "0123456789".ToCharArray();

...

string noSpaces = original.Replace(" ", "");
int lastDigit = noSpaces.LastIndexOfAny(Digits);
if (lastDigit == -1)
{
    throw new ArgumentException("No digits!");
}
string normalized = noSpaces.Insert(lastDigit, " ");

The Wikipedia entry has a lot of detail including regular expressions for validation (after normalisation :)

like image 78
Jon Skeet Avatar answered Oct 08 '22 18:10

Jon Skeet


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.

like image 22
Brandon Avatar answered Oct 08 '22 17:10

Brandon