I am programming a language interpreter in C# and have recently created a set of functions that receive either a string
or a string[]
and split it by a received string.
For example, with a string
:
"Hey:123:hello:456"
":"
It will return this array:
{"hey","123","hello","456"}
And with a string[]
:
{"a:b","c","d:e:f"}
":"
It will return this array:
{"a","b","c","d","e","f"}
How can I improve efficiency and maybe make it tidier?
public string[] SplitRows(object thevar, string delimiter) {
if (delimiter == "<newline>") delimiter = "\n";
if (thevar.GetType() == typeof(string)) {
string temp = (string) thevar;
return temp.Split(new string[] {
delimiter
}, System.StringSplitOptions.None);
}
if (thevar.GetType() == typeof(string[])) {
return stringarraysplitter((string[]) thevar, delimiter);
}
return null;
}
public string[] stringarraysplitter(string[] arr, string delimiter) {
string[][] tempr = new string[arr.Length][];
for (int i = 0; i < arr.Length; i++) {
tempr[i] = arr[i].Split(new string[] {
delimiter
}, System.StringSplitOptions.None);
}
System.Collections.Generic.List < string > templist = new System.Collections.Generic.List < string > ();
for (int i = 0; i < tempr.Length; i++) {
for (int j = 0; j < tempr[i].Length; j++) {
templist.Add(tempr[i][j]);
}
}
return templist.ToArray();
}
Side notes:
SplitRows()
is the only main function allowed to receive either a string array or string. Even though I use 2 functions, I cannot create 2 for the 2 variable types.<newline>
is a replacement string for\n
in my language and can be ignored.