I’m trying to convert parts of a string into different objects and join those into a list or array it doesn’t matter.
Here’s an example:
Sample string “This is a test string.\n \t This is a new line with a tab”.
And i would like to get an output the one one bellow:
new List<OpenXmlElement>(){
new Text("This is a test string."),
new Break(),//this is for the \n char
new TabChar(), //this is for the \t char
new Text("This is a new line with a tab")
};
I already have some the chars and the class types in a dictionary and i plan to instantiate them using reflection.
public static Dictionary<string, Type> Tags = new Dictionary<string, Type>()
{
{"\n", typeof(Break)},
{"\t", typeof(TabChar)}
};
I suppose i can doing using substrings or regex but i was hoping to find a cleaner solution.
Sorry if the question is not clear enough. I’ll be glad to answer any questions you have
This is my full class
public class FormatConverter:IFormatConverter
{
public static Dictionary<string, Type> Tags = new Dictionary<string, Type>()
{
{"\n", typeof(Break)},
{"\t", typeof(TabChar)}
};
public IEnumerable<OpenXmlElement> Convert(string format)
{
foreach (KeyValuePair<string,Type> pair in Tags)
{
var items = format.Split(
new []{pair.Key},StringSplitOptions.RemoveEmptyEntries
);
foreach (var item in items)
{
yield return new Text(item);
yield return Activator.CreateInstance(pair.Value) as OpenXmlElement;
}
format = format.Replace(pair.Key,"");
}
}
}
I know what’s wrong with it just don’t know how to fix it.
Here is a solution that parses your sample text. It may not work so well in a real situation: