您已经回答了,但这是一个涵盖更多边缘情况的实现(可能可以调整)。
public string ParseValue(string value, string trimFromStart, string trimFromEnd)
{
int valueLength = value.Length;
int trimStartAmount = value.StartsWith(trimFromStart)
? trimFromStart.Length
: 0;
int trimFromEndIndex = valueLength;
int trimEndAmount = 0;
if (value.EndsWith(trimFromEnd))
{
trimFromEndIndex = valueLength - trimFromEnd.Length;
trimEndAmount = trimFromEnd.Length;
}
if (trimStartAmount >= trimFromEndIndex)
return "";
if (trimStartAmount == 0 && trimEndAmount == 0)
return value;
return value.Substring(trimStartAmount, valueLength - trimStartAmount - trimEndAmount);
}
测试:
Assert.AreEqual("C", ParseValue("ABCDE", "AB", "DE"));
Assert.AreEqual("ABC", ParseValue("ABCDE", "ABCDEF", "DE"));
Assert.AreEqual("DE", ParseValue("ABCDE", "ABC", "ABCDEF"));
Assert.AreEqual("", ParseValue("ABCDE", "ABC", "CDE"));
Assert.AreEqual("", ParseValue("ABCDE", "ABC", "DE"));
Assert.AreEqual("BBCCCAAAB", ParseValue("AAABBBCCCAAABBB", "AAAB", "BB"));
接受的答案在测试 2、3、4 中失败,并在两个字符串重叠时引发异常。