增加string.TrimString扩展方法,可以去除头尾给定字符串
This commit is contained in:
parent
eb45aa189a
commit
e4a54ddd34
|
@ -112,5 +112,22 @@ namespace Falcon.SugarApi.Test
|
|||
Assert.IsTrue(result.Length == 1);
|
||||
Assert.IsTrue(result[0] == "abc");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 去除头尾字符
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void TestTrimString() {
|
||||
var str = @"abcabcffe222256256";
|
||||
//去除头部的abc字符
|
||||
var r = str.TrimString("abc");
|
||||
Assert.AreEqual(r , "ffe222256256");
|
||||
//去除尾部256字符
|
||||
r = str.TrimString("","256");
|
||||
Assert.AreEqual(r,"abcabcffe222");
|
||||
//去除头部abc字符和尾部256字符
|
||||
r = str.TrimString("abc","256");
|
||||
Assert.AreEqual(r,"ffe222");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -148,5 +148,38 @@ namespace Falcon.SugarApi
|
|||
i += length;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从字符串开头去除startStr字符串并从末尾去除endStr字符串,如果有多个会全部去除。
|
||||
/// </summary>
|
||||
/// <param name="str">原始字符串</param>
|
||||
/// <param name="startStr">开始处要去除的字符串,不需要则传入空字符串</param>
|
||||
/// <param name="endStr">末尾处要去除的字符串,不需要则传入空字符串</param>
|
||||
/// <returns>结果字符串</returns>
|
||||
public static string TrimString(this string str,string startStr = "",string endStr = "") {
|
||||
if(str == "") {
|
||||
return str;
|
||||
}
|
||||
if(startStr != "") {
|
||||
while(true) {
|
||||
var p = str.IndexOf(startStr);
|
||||
if(p < 0) {
|
||||
break;
|
||||
}
|
||||
str = str.Substring(p + startStr.Length);
|
||||
}
|
||||
}
|
||||
if(endStr != "") {
|
||||
while(true) {
|
||||
var p = str.LastIndexOf(endStr);
|
||||
if(p < 0) {
|
||||
break;
|
||||
}
|
||||
str = str.Substring(0,p);
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user