新增字符串扩展方法SubstringEx和Split方法。

This commit is contained in:
falcon 2022-12-09 11:17:04 +08:00
parent 2488b15532
commit 4fb6934cea
2 changed files with 140 additions and 31 deletions

View File

@ -1,4 +1,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using MySqlX.XDevAPI.Common;
using System;
using System.Linq;
namespace Falcon.SugarApi.Test namespace Falcon.SugarApi.Test
{ {
@ -13,31 +16,31 @@ namespace Falcon.SugarApi.Test
public void TestSplit() { public void TestSplit() {
var str = $"a,b.c;de。fg"; var str = $"a,b.c;de。fg";
var strArr = str.SplitStr(); var strArr = str.SplitStr();
Assert.AreEqual(7, strArr.Length, "分割后长度应该为7"); Assert.AreEqual(7,strArr.Length,"分割后长度应该为7");
str = "a,,, ,b ,c c,"; str = "a,,, ,b ,c c,";
strArr = str.SplitStr(); strArr = str.SplitStr();
Assert.AreEqual(3, strArr.Length, "分割后长度应该为3"); Assert.AreEqual(3,strArr.Length,"分割后长度应该为3");
Assert.AreEqual("a", strArr[0]); Assert.AreEqual("a",strArr[0]);
Assert.AreEqual("b", strArr[1]); Assert.AreEqual("b",strArr[1]);
Assert.AreEqual("c c", strArr[2]); Assert.AreEqual("c c",strArr[2]);
str = null; str = null;
strArr = str.SplitStr(); strArr = str.SplitStr();
Assert.IsNotNull(strArr); Assert.IsNotNull(strArr);
Assert.AreEqual(0, strArr.Length); Assert.AreEqual(0,strArr.Length);
//指定分隔符 //指定分隔符
str = $"a,b.c;de。fg"; str = $"a,b.c;de。fg";
strArr = str.SplitStr(','); strArr = str.SplitStr(',');
Assert.AreEqual(2, strArr.Length, "分割后长度应该为7"); Assert.AreEqual(2,strArr.Length,"分割后长度应该为7");
Assert.AreEqual("a", strArr[0]); Assert.AreEqual("a",strArr[0]);
Assert.AreEqual("b.c;de。fg", strArr[1]); Assert.AreEqual("b.c;de。fg",strArr[1]);
strArr = str.SplitStr(',', '.'); strArr = str.SplitStr(',','.');
Assert.AreEqual(3, strArr.Length, "分割后长度应该为7"); Assert.AreEqual(3,strArr.Length,"分割后长度应该为7");
Assert.AreEqual("a", strArr[0]); Assert.AreEqual("a",strArr[0]);
Assert.AreEqual("b", strArr[1]); Assert.AreEqual("b",strArr[1]);
Assert.AreEqual("c;de。fg", strArr[2]); Assert.AreEqual("c;de。fg",strArr[2]);
} }
/// <summary> /// <summary>
@ -48,13 +51,67 @@ namespace Falcon.SugarApi.Test
var str = ""; var str = "";
var r = ""; var r = "";
r = str.ToDefault("abc"); r = str.ToDefault("abc");
Assert.AreEqual("abc", r); Assert.AreEqual("abc",r);
str = null; str = null;
r = str.ToDefault("abc"); r = str.ToDefault("abc");
Assert.AreEqual("abc", r); Assert.AreEqual("abc",r);
str = "123"; str = "123";
r = str.ToDefault("abc"); r = str.ToDefault("abc");
Assert.AreEqual("123", r); Assert.AreEqual("123",r);
}
/// <summary>
/// 检索子字符串测试
/// </summary>
[TestMethod]
public void TestSubstringEx() {
var str = "abcd33";
string r;
r = str.SubstringEx(str.Length + 1,1);
Assert.IsTrue(r == "");
r = str.SubstringEx(0,0);
Assert.IsTrue(r == "");
r = str.SubstringEx(3,-1);
Assert.IsTrue(r == "c");
r = str.SubstringEx(3,10);
Assert.IsTrue(r == "d33");
r = str.SubstringEx(-1,2);
Assert.IsTrue(r == "a");
r = str.SubstringEx(1,2);
Assert.IsTrue(r == "bc");
}
/// <summary>
/// 按一定长度分割字符串测试
/// </summary>
[TestMethod]
public void TestSplitByLength() {
string str;
string[] result;
str = "";
Assert.ThrowsException<ArgumentNullException>(() => { result = str.Split(5).ToArray(); });
str = "abc";
Assert.ThrowsException<Exception>(() => { result = str.Split(0).ToArray(); });
result = str.Split(1).ToArray();
Assert.IsTrue(result.Length == 3);
Assert.IsTrue(result[0] == "a");
Assert.IsTrue(result[1] == "b");
Assert.IsTrue(result[2] == "c");
result = str.Split(2).ToArray();
Assert.IsTrue(result.Length == 2);
Assert.IsTrue(result[0] == "ab");
Assert.IsTrue(result[1] == "c");
result = str.Split(3).ToArray();
Assert.IsTrue(result.Length == 1);
Assert.IsTrue(result[0] == "abc");
result = str.Split(4).ToArray();
Assert.IsTrue(result.Length == 1);
Assert.IsTrue(result[0] == "abc");
} }
} }
} }

View File

@ -1,6 +1,9 @@
using System; using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Linq;
using System.Reflection.Metadata;
namespace Falcon.SugarApi namespace Falcon.SugarApi
{ {
@ -28,7 +31,7 @@ namespace Falcon.SugarApi
/// <param name="str">字符串</param> /// <param name="str">字符串</param>
/// <param name="defaultVal">默认值</param> /// <param name="defaultVal">默认值</param>
/// <returns>字符串本身或默认值</returns> /// <returns>字符串本身或默认值</returns>
public static string? ToDefault(this string? str, [NotNull] string defaultVal) => str.IsNullOrEmpty() ? defaultVal : str; public static string? ToDefault(this string? str,[NotNull] string defaultVal) => str.IsNullOrEmpty() ? defaultVal : str;
/// <summary> /// <summary>
/// 使用全角半角的逗号句号和分号分割字符串。 /// 使用全角半角的逗号句号和分号分割字符串。
@ -36,8 +39,8 @@ namespace Falcon.SugarApi
/// <param name="str">要分割的字符串</param> /// <param name="str">要分割的字符串</param>
/// <param name="splitChars"></param> /// <param name="splitChars"></param>
/// <returns>字符串数组。当str为null时返回空数组</returns> /// <returns>字符串数组。当str为null时返回空数组</returns>
public static string[] SplitStr(this string? str, params char[] splitChars) public static string[] SplitStr(this string? str,params char[] splitChars)
=> str.IsNullOrEmpty() ? Array.Empty<string>() : str.Split(splitChars.Length == 0 ? new char[] { ',', '', ';', '', '.', '。' } : splitChars, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); => str.IsNullOrEmpty() ? Array.Empty<string>() : str.Split(splitChars.Length == 0 ? new char[] { ',','',';','','.','。' } : splitChars,StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
/// <summary> /// <summary>
@ -47,12 +50,12 @@ namespace Falcon.SugarApi
/// <param name="dateTimeFormat">时间格式</param> /// <param name="dateTimeFormat">时间格式</param>
/// <param name="culture">区域特性.默认CultureInfo.InvariantCulture</param> /// <param name="culture">区域特性.默认CultureInfo.InvariantCulture</param>
/// <returns>时间</returns> /// <returns>时间</returns>
public static DateTime ToDateTime(this string str, string dateTimeFormat = "", CultureInfo? culture = null) { public static DateTime ToDateTime(this string str,string dateTimeFormat = "",CultureInfo? culture = null) {
culture ??= CultureInfo.InvariantCulture; culture ??= CultureInfo.InvariantCulture;
if (dateTimeFormat.IsNullOrEmpty()) { if(dateTimeFormat.IsNullOrEmpty()) {
return DateTime.Parse(str); return DateTime.Parse(str);
} }
return DateTime.ParseExact(str, dateTimeFormat, culture); return DateTime.ParseExact(str,dateTimeFormat,culture);
} }
/// <summary> /// <summary>
/// 尝试将特定格式字符串转换为DateTime类型 /// 尝试将特定格式字符串转换为DateTime类型
@ -62,12 +65,11 @@ namespace Falcon.SugarApi
/// <param name="dt">转换后的时间</param> /// <param name="dt">转换后的时间</param>
/// <param name="culture">区域特性.默认CultureInfo.InvariantCulture</param> /// <param name="culture">区域特性.默认CultureInfo.InvariantCulture</param>
/// <returns>成功True失败False</returns> /// <returns>成功True失败False</returns>
public static bool TryToDateTime(this string str, string dateTimeFormat, out DateTime dt, CultureInfo? culture = null) { public static bool TryToDateTime(this string str,string dateTimeFormat,out DateTime dt,CultureInfo? culture = null) {
try { try {
dt = str.ToDateTime(dateTimeFormat, culture); dt = str.ToDateTime(dateTimeFormat,culture);
return true; return true;
} } catch(Exception) {
catch (Exception) {
dt = default; dt = default;
return false; return false;
} }
@ -80,14 +82,64 @@ namespace Falcon.SugarApi
/// <param name="dateFormat">日期时间格式</param> /// <param name="dateFormat">日期时间格式</param>
/// <returns>是True否False</returns> /// <returns>是True否False</returns>
/// <exception cref="ArgumentNullException">参数为空</exception> /// <exception cref="ArgumentNullException">参数为空</exception>
public static bool IsDateFormat(this string str, string dateFormat) { public static bool IsDateFormat(this string str,string dateFormat) {
if (str.IsNullOrEmpty()) { if(str.IsNullOrEmpty()) {
throw new ArgumentNullException(nameof(str)); throw new ArgumentNullException(nameof(str));
} }
if (dateFormat.IsNullOrEmpty()) { if(dateFormat.IsNullOrEmpty()) {
throw new ArgumentNullException(nameof(dateFormat)); throw new ArgumentNullException(nameof(dateFormat));
} }
return str.TryToDateTime(dateFormat, out var _); return str.TryToDateTime(dateFormat,out var _);
}
/// <summary>
/// 获取子字符串
/// <para>如果start大于字符串长度或者length等于0则返回空字符串。</para>
/// <para>如果length小于0则返回start前面长度的字符串。</para>
/// <para>如果字符串不满足需要的长度要求则返回实际长度字符串。</para>
/// <para>如果start小于0则返回从0开始的length+start长度字符串。</para>
/// </summary>
/// <param name="str">要检索的字符串</param>
/// <param name="start">开始位置</param>
/// <param name="length">获取长度</param>
/// <returns>子字符串</returns>
/// <exception cref="Exception">获取长度不满足要求</exception>
public static string SubstringEx(this string str,int start,int length) {
if(start > str.Length || length == 0) {
return "";
}
if(length < 0) {
start = start + length;
length = -length;
}
if(start < 0) {
length += start;
start = 0;
}
if(start + length > str.Length) {
return str.Substring(start);
}
return str.Substring(start,length);
}
/// <summary>
/// 按照固定长度分割字符串
/// </summary>
/// <param name="str">要分割的字符串</param>
/// <param name="length">分割长度</param>
/// <returns>分割后的字符串枚举</returns>
public static IEnumerable<string> Split(this string str,int length) {
if(length <= 0) {
throw new Exception("分割长度必须大于0");
}
if(str.IsNullOrEmpty()) {
throw new ArgumentNullException(nameof(str));
}
int i = 0;
while(str.Length > i) {
yield return str.SubstringEx(i,length);
i += length;
}
} }
} }
} }