I have a code for conversion but some address have different result to what is expected.
23 Starling St => 3 Streetarling Street which is wrong and it should be 23 Starling Street
1 St Johns Ct => 1 Street Johns Ct => Correct
This is the code:
private string StreetConversion(string address, Order order)
{
string[] addressList = address.Split(' ');
foreach (string add in addressList)
{
if(add == "pde")
address = address.Replace("pde", "Parade");
if (add == "Pde")
address = address.Replace("Pde", "Parade");
if (add == "Rd")
address = address.Replace("Rd", "Road");
if (add == "rd")
address = address.Replace("rd", "Road");
if (add == "St")
address = address.Replace("St", "Street");
if (add == "st")
address = address.Replace("st", "Street");
}
order.ShipAddress1 = address;
return address;
}
You need to replace given word instead of replacing all occurences of that word in address variable,
private string StreetConversion(string address, Order order)
{
string[] addressList = address.Split(' ');
StringBuilder newAddress = new StringBuilder();
foreach (string add in addressList)
{
if(add.ToLower() == "pde")
newAddress.Append("Parade ");
else if (add.ToLower() == "rd")
newAddress.Append("Road ");
else if (add.ToLower() == "st")
newAddress.Append("Street ");
else
newAddress.Append(add+ " ");
}
order.ShipAddress1 = newAddress.ToString();
return newAddress.ToString();
}
First of all, let's extract model: acronyms and their substitutions
private static Dictionary<string, string> acronyms =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{"pde", "Parade"},
{"rd", "Road"},
{"st", "Street"},
//TODO: Add more pairs if required, say, {"sq", "square"},
};
Then we can easily transform the string address:
using System.Linq;
...
private string StreetConversion(string address, Order order) {
string result = string.Join(" ", address
.Split(' ')
.Select(word => acronyms.TryGetValue(word, out var newWord) ? newWord : word));
order.ShipAddress1 = result;
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With