How do I parse a string in C# to extract key-value pairs without any delimiters between key and value?
I have a string that looks like this
string str = "\nFIRSTNAMEJOHN\nLASTNAMESMITH\nADDRESS1590 GRACE STREET\nBIRTHDATE04201969"
After splitting on \n I get a collection of strings that looks like
string[] properties = ["FIRSTNAMEJOHN","LASTNAMESMITH", etc.]
I want to loop through the split array of these strings and extract the key-value pair from each individual string, so that I can populate the properties of an object such as...
Person person = new Person()
{ FIRSTNAME = JOHN,
LASTNAME = SMITH,
etc...
}
What is the cleanest way of doing this? Thanks!
You could create a class that has those properties, then get the properties of the object through reflection (so we can use a loop), split the string on the \n
character, then for each property, and for each setting, if the setting starts with the property name, set the property value based on the rest of the setting string.
For example:
class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string BirthDate { get; set; }
public override string ToString()
{
return $"{FirstName} {LastName}, born on {BirthDate}, lives at: {Address}";
}
}
public class Program
{
static void Main(string[] args)
{
string str = "\nFIRSTNAMEJOHN\nLASTNAMESMITH\nADDRESS1590 GRACE STREET\nBIRTHDATE04201969";
var user = new User();
var properties = typeof(User).GetProperties();
var settings = str.Split('\n');
foreach (var property in properties)
{
foreach (var setting in settings)
{
if (setting.StartsWith(property.Name, StringComparison.OrdinalIgnoreCase))
{
property.SetValue(user, setting.Substring(property.Name.Length));
break;
}
}
}
Console.WriteLine(user);
GetKeyFromUser("\n\nDone! Press any key to exit...");
}
}
Output