检测字符串中的前导零

时间:2015-01-29 23:43:29

标签: c# .net

我目前正试图检测一个数字是否有前导零。不确定检测它的最佳方法是什么。一个例子就是这样的" 000445454"

3 个答案:

答案 0 :(得分:8)

使用String.StartsWith

“确定此字符串实例的开头是否与指定的字符串匹配。”

string numbers =  "000445454";
if (numbers.StartsWith("0"))
    //Do Something

答案 1 :(得分:0)

string str = "0";
if(str.StartsWith("0") && str.Length !=1) Console.WriteLine("false");
else Console.WriteLine("true");

如果字符串以'0'开头,并且有多个字符。

答案 2 :(得分:0)

我不熟悉 c# 语法

但是在 C++ 中,为了找到 00, 05, 01 ,我倾向于这样做:

我们可以使用

找到左起第一个零的索引
index = str.find('0');

现在检查 index == 0 是否表示前导零并且字符串的长度大于 1

if(index ==0 and str.length()>1){
    cout<<"Leading Zero";
}