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

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!

Advertisements