c#字符串的非空的判断

我们都知道,string.IsNullOrEmpty方法是判断字符串是否为:null或者string.Empty;string.IsNullOrWhiteSpace方法是判断null或者所有空白字符,功能相当于string.IsNullOrEmpty和str.Trim().Length总和。

也就是说如果字符串未连续的空格的话,是可以通过string.IsNullOrEmpty 的。而不会通过string.IsNullOrWhiteSpace

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你要判断两个 C# 字符串在一定程度上的相似度,可以使用模糊相等的方法。具体方法如下: 1. 使用 Levenshtein 距离算法计算两个字符串的编辑距离(也叫 Levenshtein 距离),即将一个字符串转换成另一个字符串所需的最少编辑操作次数。编辑操作包括插入、删除、替换字符。 2. 根据 Levenshtein 距离算法的计算结果,设置一个阈值,如果两个字符串的编辑距离小于等于这个阈值,则判断它们相似。 3. 可以根据实际需要,结合其他算法或规则,对相似度进行更精细的判断。 下面是一个示例代码: ```csharp public static bool IsFuzzyEqual(string str1, string str2, int threshold) { if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) return false; // 计算两个字符串的 Levenshtein 距离 int[,] d = new int[str1.Length + 1, str2.Length + 1]; for (int i = 0; i <= str1.Length; i++) d[i, 0] = i; for (int j = 0; j <= str2.Length; j++) d[0, j] = j; for (int i = 1; i <= str1.Length; i++) { for (int j = 1; j <= str2.Length; j++) { int cost = (str1[i - 1] == str2[j - 1]) ? 0 : 1; d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // 判断两个字符串的相似度 int distance = d[str1.Length, str2.Length]; return distance <= threshold; } ``` 使用示例: ```csharp string str1 = "Hello, World!"; string str2 = "Hello, world!"; bool isFuzzyEqual = IsFuzzyEqual(str1, str2, 2); Console.WriteLine(isFuzzyEqual); // 输出 True ``` 上述代码中,我设置的阈值是 2,表示两个字符串的编辑距离小于等于 2 时,认为它们相似。你可以根据实际需要,设置不同的阈值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值