Java如何删除数值字符串左侧前导零直至第一个非零字符
删除数值字符串前导零的可行方案
核心实现逻辑为:定位到字符串中第一个非零字符的下标,从该位置向后截取完整字符串即可,注意额外处理全零字符串(如"000000")的场景,避免返回空值。
以下是不同主流编程语言的实现示例:
Python 实现
直接使用内置的lstrip方法即可,该方法仅移除字符串左侧的指定字符,不会影响字符串中间和末尾的字符:
def remove_leading_zeros(s: str) -> str: res = s.lstrip('0') # 处理全零场景,避免返回空串 return res if res else '0' # 测试用例 print(remove_leading_zeros("00000545468")) # 输出:545468 print(remove_leading_zeros("00002021")) # 输出:2021 print(remove_leading_zeros("000000001990")) # 输出:1990 print(remove_leading_zeros("000000")) # 输出:0
如果不想用内置方法,也可以手动遍历定位首个非零字符:
def remove_leading_zeros(s: str) -> str: for idx, char in enumerate(s): if char != '0': return s[idx:] # 遍历完所有字符都为0的情况 return '0'
JavaScript 实现
正则方案
function removeLeadingZeros(s) { const res = s.replace(/^0+/, ''); return res || '0'; }
手动遍历方案
function removeLeadingZeros(s) { let startIdx = 0; while(startIdx < s.length && s[startIdx] === '0') { startIdx++; } return startIdx === s.length ? '0' : s.slice(startIdx); }
Java 实现
public class RemoveLeadingZeros { public static String removeLeadingZeros(String s) { int startIdx = 0; while (startIdx < s.length() && s.charAt(startIdx) == '0') { startIdx++; } return startIdx == s.length() ? "0" : s.substring(startIdx); } public static void main(String[] args) { System.out.println(removeLeadingZeros("00002021")); // 输出:2021 System.out.println(removeLeadingZeros("000000001990")); // 输出:1990 } }
内容的提问来源于stack exchange,提问作者cave lupum
相关产品推荐
相关产品推荐

