Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Replace c# for address abbreviation

Tags:

c#

replace

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;
}
like image 447
Jen143 Avatar asked Sep 10 '26 05:09

Jen143


2 Answers

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();
}
like image 50
Prasad Telkikar Avatar answered Sep 11 '26 18:09

Prasad Telkikar


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;  
  }
like image 33
Dmitry Bychenko Avatar answered Sep 11 '26 18:09

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!