I have the following C# method to split a path string. The only thing I know is a fixed string in the path and I have to split the full path into two parts, first part should be one level below the fixed string and the rest should be the second part.
For example, if I have the following path:
string mainText = @"C:\Abc\Fixed\MyTemp\Japan\Tokyo";
then my firstPart would be "C:\Abc\Fixed\MyTemp"
and second part "Japan\Tokyo"
I want to improve this method in terms of memory and speed.
private static void SplitPath(string mainText, out string firstPart, out string secondPart)
{
firstPart = string.Empty;
secondPart = string.Empty;
if (!string.IsNullOrEmpty(mainText))
{
string strConstatnt = "Fixed";
List<string> splitted = mainText.Split(new char[] { '\\' }).ToList();
int indexToFixed = splitted.IndexOf(strConstatnt);
StringBuilder sbFirst = new StringBuilder();
StringBuilder sbSecond = new StringBuilder();
if (indexToFixed >= 0)
{
for (int i = 0; i < splitted.Count; i++)
{
if (i < (indexToFixed + 2))
{
sbFirst.Append(splitted[i] + "\\");
}
else
{
break;
}
}
for (int i = (indexToFixed + 2); i < splitted.Count; i++)
{
sbSecond.Append(splitted[i] + "\\");
}
}
if (sbFirst.Length > 0)
{
firstPart = sbFirst.Remove(sbFirst.Length - 1, 1).ToString();
}
if (sbSecond.Length > 0)
{
secondPart = sbSecond.Remove(sbSecond.Length - 1, 1).ToString();
}
}
}