|
|
Webmaster posted on January 03, 2025 12:24
You can split an address string like "120 old Freemans Way" into the house number and street name in C# using several approaches.
Use Regex.Match
(Recommended for robustness):
This method uses regular expressions to find the first sequence of digits at the beginning of the string. This is generally the most robust approach as it handles variations in spacing and potential non-numeric characters after the house number.
using System;
using System.Text.RegularExpressions;
public class AddressSplitter
{
public static (string HouseNumber, string StreetName) SplitAddress(string address)
{
if (string.IsNullOrEmpty(address))
{
return ("", ""); // Or throw an exception if appropriate
}
Match match = Regex.Match(address, @"^(\d+)\b\s*(.*)");
if (match.Success)
{
string houseNumber = match.Groups[1].Value;
string streetName = match.Groups[2].Value.Trim(); // Trim extra whitespace
return (houseNumber, streetName);
}
else
{
return ("", address.Trim()); // Handle cases where no house number is found
}
}
public static void Main(string[] args)
{
string address = "120 old Freemans Way";
(string houseNumber, string streetName) = SplitAddress(address);
Console.WriteLine($"House Number: {houseNumber}");
Console.WriteLine($"Street Name: {streetName}");
address = "120A old Freemans Way"; //Handles letters after number
(houseNumber, streetName) = SplitAddress(address);
Console.WriteLine($"House Number: {houseNumber}");
Console.WriteLine($"Street Name: {streetName}");
address = "old Freemans Way"; //Handles no number
(houseNumber, streetName) = SplitAddress(address);
Console.WriteLine($"House Number: {houseNumber}");
Console.WriteLine($"Street Name: {streetName}");
address = " 120 old Freemans Way"; //Handles leading spaces
(houseNumber, streetName) = SplitAddress(address);
Console.WriteLine($"House Number: {houseNumber}");
Console.WriteLine($"Street Name: {streetName}");
}
}
There are currently no comments, be the first to post one!