看起来没有简单的方法,因为string.Trim()
内部使用两种不同的方法.
用于空格的TrimWhiteSpaceHelper:
private string TrimWhiteSpaceHelper(TrimType trimType)
{
// end will point to the first non-trimmed character on the right.
// start will point to the first non-trimmed character on the left.
int end = Length - 1;
int start = 0;
// Trim specified characters.
if ((trimType & TrimType.Head) != 0)
{
for (start = 0; start < Length; start++)
{
if (!char.IsWhiteSpace(this[start]))
{
break;
}
}
}
if ((trimType & TrimType.Tail) != 0)
{
for (end = Length - 1; end >= start; end--)
{
if (!char.IsWhiteSpace(this[end]))
{
break;
}
}
}
return CreateTrimmedString(start, end);
}
和用于自定义字符的TrimHelper:
private unsafe string TrimHelper(char* trimChars, int trimCharsLength, TrimType trimType)
{
Debug.Assert(trimChars != null);
Debug.Assert(trimCharsLength > 0);
// end will point to the first non-trimmed character on the right.
// start will point to the first non-trimmed character on the left.
int end = Length - 1;
int start = 0;
// Trim specified characters.
if ((trimType & TrimType.Head) != 0)
{
for (start = 0; start < Length; start++)
{
int i = 0;
char ch = this[start];
for (i = 0; i < trimCharsLength; i++)
{
if (trimChars[i] == ch)
{
break;
}
}
if (i == trimCharsLength)
{
// The character is not in trimChars, so stop trimming.
break;
}
}
}
if ((trimType & TrimType.Tail) != 0)
{
for (end = Length - 1; end >= start; end--)
{
int i = 0;
char ch = this[end];
for (i = 0; i < trimCharsLength; i++)
{
if (trimChars[i] == ch)
{
break;
}
}
if (i == trimCharsLength)
{
// The character is not in trimChars, so stop trimming.
break;
}
}
}
return CreateTrimmedString(start, end);
}
将它们组合在一起可能看起来像这样:
public static class TrimmerExtension
{
public static string TrimWhitespaceAndPrefixes(this string str, params char[] trimChars)
{
var trimCharsLength = trimChars.Length;
int start;
for (start = 0; start < str.Length; start++)
{
var ch = str[start];
if (!char.IsWhiteSpace(ch))
{
int i;
for (i = 0; i < trimCharsLength; i++)
{
if (trimChars[i] == ch)
{
break;
}
}
if (i == trimCharsLength)
{
break;
}
}
}
return str[start..];
}
}
如果性能不是很重要,我建议使用正则表达式或从https://stackoverflow.com/a/76133168/2770274开始的速记版本