using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text.RegularExpressions;
|
|
namespace JiepeiWMS.Common.Helper
|
{
|
public class StringHelper
|
{
|
/// <summary>
|
/// 根据分隔符返回前n条数据
|
/// </summary>
|
/// <param name="content">数据内容</param>
|
/// <param name="separator">分隔符</param>
|
/// <param name="top">前n条</param>
|
/// <param name="isDesc">是否倒序(默认false)</param>
|
/// <returns></returns>
|
public static List<string> GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false)
|
{
|
if (string.IsNullOrEmpty(content))
|
{
|
return new List<string>() { };
|
}
|
|
if (string.IsNullOrEmpty(separator))
|
{
|
throw new ArgumentException("message", nameof(separator));
|
}
|
|
var dataArray = content.Split(separator).Where(d => !string.IsNullOrEmpty(d)).ToArray();
|
if (isDesc)
|
{
|
Array.Reverse(dataArray);
|
}
|
|
if (top > 0)
|
{
|
dataArray = dataArray.Take(top).ToArray();
|
}
|
|
return dataArray.ToList();
|
}
|
|
/// <summary>
|
/// 获取字符串中的数字
|
/// </summary>
|
/// <param name="str">字符串</param>
|
/// <returns>数字</returns>
|
public static decimal GetNumber(string str)
|
{
|
decimal result = 0;
|
if (str != null && str != string.Empty)
|
{
|
// 正则表达式剔除非数字字符(不包含小数点.)
|
//str = Regex.Replace(str, @"[^/d./d]", "");
|
str = Regex.Replace(str, @"[^\d.\d]", "");
|
// 如果是数字,则转换为decimal类型
|
if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
|
{
|
result = decimal.Parse(str);
|
}
|
}
|
return result;
|
}
|
|
/// <summary>
|
/// 获取字符串中的数字
|
/// </summary>
|
/// <param name="str">字符串</param>
|
/// <returns>数字</returns>
|
public static decimal GetNumberInt(string str)
|
{
|
decimal result = 0;
|
if (str != null && str != string.Empty)
|
{
|
// 正则表达式剔除非数字字符(不包含小数点.)
|
str = Regex.Replace(str, @"[^\d.\d]", "");
|
// 如果是数字,则转换为decimal类型
|
if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
|
{
|
result = int.Parse(str);
|
}
|
}
|
return result;
|
}
|
}
|
}
|