For the two examples given:
const string prefix = "StackLevel";
const string suffix = "Item";
public static string GetCentralPart(string str)
{
if (str == null)
{
return str;
}
if (!str.StartsWith(prefix) || !str.EndsWith(suffix))
{
return str;
}
return str.Substring(prefix.Length, str.Length - prefix.Length - suffix.Length);
}
Use:
string str = "StackLevelThreeItem";
string centralPart = GetCentralPart(str);
The code is quite linear... The only interesting points are the use of some const string
for the prefix/suffix, the use of StartsWith
/EndsWith
to check that the string really has the prefix/suffix, and how the Substring
length is calculated.