簡體   English   中英

檢測字符串中的前導零

[英]Detect Leading Zero in String

我目前正在嘗試檢測一個數字是否有前導零。 不知道什么是最好的檢測方法。 一個例子是這樣的“000445454”

使用String.StartsWith

“確定此字符串實例的開頭是否與指定的字符串匹配。”

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

在非空的“s”字符串中檢測前導零的一種簡單方法是將其第一個元素與字符“0”進行比較:

s[0] == '0'

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

如果字符串以'0'開頭並且它有多個字符。

我不熟悉 c# 語法

但是在C++中,為了找到00, 05, 01 ,我傾向於這樣做:

我們可以使用從左邊找到第一個零的索引

index = str.find('0');

現在檢查 index == 0 是否意味着前導零並且字符串的長度大於 1

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM