C# string 扩展方法

持续更新中...

 
1. string转枚举

public static class StringExtensions
{
    public static T ToEnum<T>(this string str)
    {
        try
        {
            return (T)Enum.Parse(typeof(T), str);
        }
        catch
        {
            return default;
        }
    }
}

示例代码

string value = "Monday";
DayOfWeek day = value.ToEnum<DayOfWeek>();

2. 移除所有非汉字、字母、数字的字符

public static string RemoveTitleSymbol(this string str)
{
     return Regex.Replace(str, @"[^\u4e00-\u9fa5a-zA-Z0-9]", "");
}

示例代码

string originalString = "这是 一段 含有 宫格 的 字符串,123!@#";
string filteredString = originalString.RemoveTitleSymbol();

3. 移除空格

public static string RemoveSpace(this string str)
{
    return Regex.Replace(str, @"\s", "");
}

示例代码

string originalString = "这是 一段 含有 宫格 的 字符串";
string filteredString = originalString.RemoveSpace();

4.判断文件是否存在

public static bool IsFileExist(this string path)
{
       // 判断文件路径是否为空或空白字符串
      if (string.IsNullOrWhiteSpace(path))
      {
          throw new ArgumentException("File path is null or empty.");
      }
      return System.IO.File.Exists(path);
}

示例代码

string filePath = "C:/example/file.txt"; 
bool fileExist = filePath.IsFileExist();
Debug.Log(fileExist);

5.根据路径创建文件夹

 public static void CreateFolder(this string path)
{
     // 判断文件夹路径是否为空或空白字符串
    if (string.IsNullOrWhiteSpace(path))
    {
       throw new ArgumentException("Folder path is null or empty.");
    }

    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
}

示例代码

string folderPath = "C:/example/folder"; 
folderPath.CreateFolder(); 

6.URL中提取文件名

public static string ExtractFileNameFromUrl(this string url)
    {
        if (string.IsNullOrEmpty(url))
            return string.Empty;

        if (Uri.TryCreate(url, UriKind.Absolute, out var uri))
        {
            // 提取路径部分
            string path = uri.AbsolutePath;
            // 获取最后一个斜杠后的字符串,即文件名
            int lastSlashIndex = path.LastIndexOf('/');
            if (lastSlashIndex >= 0 && lastSlashIndex < path.Length - 1)
            {
                return path.Substring(lastSlashIndex + 1);
            }
        }

        return string.Empty;
    }

示例代码

string  downloadUrl = "http://example.com/file.zip";
var fileName = downloadUrl.ExtractFileNameFromUrl();

  • 21
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天喝水了嘛.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值