Normalizing postcode in C#

In many web applications, you need to ask user a postcode to display list of addresses so that user can select the relevant one.

User can enter in any format like as shown below (and they all are valid ones)

M1 1AA or M11AA

M60 1NW or M601NW

EC1A 1BB or EC1A1BB

so how to go about sending it in the right format to fetch data?

Simple string functions like Trim(), Replace() and Insert() would come handy.

Consider the following function


public static string NormalizePostcode(string postcode)
{
//removes end and start spaces
postcode = postcode.Trim();
//removes in middle spaces
postcode = postcode.Replace(" ", "");
switch (postcode.Length) {
//add space after 2 characters if length is 5
case 5: temp_postcode = temp_postcode.Insert(2, " "); break;
//add space after 3 characters if length is 6
case 6: temp_postcode = temp_postcode.Insert(3, " "); break;
//add space after 4 characters if length is 7
case 7: temp_postcode = temp_postcode.Insert(4, " "); break;
default: break;
}
return postcode;
}

Explanation of the code:
1. It trims the postcode that is remove any unwanted starting or ending blank spaces

2. It would remove any spaces enter in the middle

3. So now we have a normalized postcode, which we could manipulate.

4. Using a switch on length of string, we could insert a blank space where ever we want

5. Returns the postcode that we want.

The code is given in C# but I am sure it can be adopted in any lanugage, and I hope my Sat Nav people see this post!

4 thoughts on “Normalizing postcode in C#

  1. Thanks friend for the Great share of information, it was very helpful to me. I really like the manner in which you have presented your concern regarding this matter, keep up the awesome work. All the Best. John

  2. I agree with Lawrence… The space is always in the place (4 chars in from the right) so why use a switch statement when the position is constant? Seems really messy.

    1. It’s not always 4 from the right though. Some are 2, some are 3 are some are 4 (depending on overall length). Hence this solution…

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.