我正在寻找String扩展方法,TrimStart()并TrimEnd()接受一个字符串参数.
我自己可以建立一个,但我总是对看别人如何做事感兴趣.
如何才能做到这一点?
Pat*_*ald 87
要修剪(完全匹配)字符串的所有匹配项,您可以使用以下内容:
public static string TrimStart(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.StartsWith(trimString))
{
result = result.Substring(trimString.Length);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
public static string TrimEnd(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.EndsWith(trimString))
{
result = result.Substring(0, result.Length - trimString.Length);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
要从目标的开始/结束修剪trimChars中的任何字符(例如,"foobar'@"@';".TrimEnd(";@'")将返回"foobar"),您可以使用以下内容:
public static string TrimStart(this string target, string trimChars)
{
return target.TrimStart(trimChars.ToCharArray());
}
Run Code Online (Sandbox Code Playgroud)
public static string TrimEnd(this string target, string trimChars)
{
return target.TrimEnd(trimChars.ToCharArray());
}
Run Code Online (Sandbox Code Playgroud)
Run*_*tad 16
TrimStart和TrimEnd接收一组字符.这意味着您可以将字符串作为char数组传递,如下所示:
var trimChars = " .+-";
var trimmed = myString.TrimStart(trimChars.ToCharArray());
Run Code Online (Sandbox Code Playgroud)
所以我认为不需要带有字符串参数的重载.
Tim*_*Tim 12
我认为问题是试图从一个较大的字符串的开头修剪一个特定的字符串.
例如,如果我有字符串"hellohellogoodbyehello",如果你试图调用TrimStart("你好"),你会得到"goodbyehello".
如果是这种情况,您可以使用如下代码:
string TrimStart(string source, string toTrim)
{
string s = source;
while (s.StartsWith(toTrim))
{
s = s.Substring(toTrim.Length - 1);
}
return s;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要进行大量的字符串修剪,这将不会超级高效,但如果仅仅针对少数情况,那么它很简单并且可以完成工作.
要匹配整个字符串而不分配多个子字符串,您应该使用以下命令:
public static string TrimStart(this string source, string value, StringComparison comparisonType)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
int valueLength = value.Length;
int startIndex = 0;
while (source.IndexOf(value, startIndex, comparisonType) == startIndex)
{
startIndex += valueLength;
}
return source.Substring(startIndex);
}
public static string TrimEnd(this string source, string value, StringComparison comparisonType)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
int sourceLength = source.Length;
int valueLength = value.Length;
int count = sourceLength;
while (source.LastIndexOf(value, count, comparisonType) == count - valueLength)
{
count -= valueLength;
}
return source.Substring(0, count);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65902 次 |
| 最近记录: |