You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将SQL Server中基于Substring与Patindex的去除前导零逻辑转换为C#代码

将SQL Server去前导零逻辑转换为C#代码

没问题,我帮你把这段SQL的去前导零逻辑转换成C#代码,先拆解下原SQL的核心逻辑,再给出对应实现:
原SQL的核心逻辑是:找到字符串中第一个不是0也不是空格的字符位置,从该位置截取到末尾;如果字符串全是0(或空格+0),最终返回单个'0'。

下面提供两种常用的C#实现方案:

方案一:正则表达式实现(简洁直观)

这种方式代码量少,适合快速落地:

public static string RemoveLeadingZeros(string input)
{
    if (string.IsNullOrWhiteSpace(input))
        return "0";
    
    // 替换开头所有的0和空格
    string result = System.Text.RegularExpressions.Regex.Replace(input, @"^[0\s]+", "");
    
    // 若替换后为空(说明原字符串全是0/空格),返回"0"
    return string.IsNullOrEmpty(result) ? "0" : result;
}

测试你的示例场景:

  • 输入"001" → 输出"1"
  • 输入"00" → 输出"0"
  • 输入"00013025990" → 输出"13025990"

方案二:手动遍历实现(性能更优)

如果需要处理大量字符串,手动遍历的性能会比正则表达式更好:

public static string RemoveLeadingZeros(string input)
{
    if (string.IsNullOrWhiteSpace(input))
        return "0";
    
    int firstValidCharIndex = 0;
    // 找到第一个不是0也不是空格的字符索引
    while (firstValidCharIndex < input.Length)
    {
        char currentChar = input[firstValidCharIndex];
        if (currentChar != '0' && currentChar != ' ')
            break;
        firstValidCharIndex++;
    }
    
    // 所有字符都是0/空格,返回"0"
    if (firstValidCharIndex == input.Length)
        return "0";
    
    // 从第一个有效字符位置截取到末尾
    return input.Substring(firstValidCharIndex);
}

两种方案都完全匹配原SQL的逻辑:既保留了对前导空格和零的处理,也正确覆盖了全零的边界场景。

内容的提问来源于stack exchange,提问作者avnish maddheshiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:44:23