字串是否為某個型別的數值

2021-08-30 10:33:38 字數 1552 閱讀 9288

有時候需要判斷乙個字串是不是乙個int/double/float.

c#沒有直接的方法實現,可以自己用如下幾個方法實現:

<1>try-catch

class program

catch

}

static void main(string args)

!", str = (isint32(str) ? "yes":"no")); }}

<2>正規表示式

using system.text.regularexpressions;

class program

!", str = (rex.ismatch(str) ? "yes" : "no")); }}

效率比較

class program

catch

}public static bool isnumber(string s)

return true;

}static void main(string args)

counter = system.environment.tickcount - counter;

isn = counter;

console.writeline("innumber time:ms!", isn);

counter = system.environment.tickcount;

for (int i = 0; i < times; i++)

counter = system.environment.tickcount - counter;

rx = counter;

console.writeline("regex time:ms!", rx);

counter = system.environment.tickcount;

for (int i = 0; i < times; i++)

counter = system.environment.tickcount - counter;

tc = counter;

console.writeline("trycatch time:ms!", tc);

console.writeline("innumber:regex:trycatch = : : ",tc/isn, tc/rx, tc/tc);

"innumber:trycatch:regex = : : ",rx/isn, rx/tc, rx/rx);

}

可以發現,trycatch 在有沒有丟擲異常的情況下,差別很大。

要是有異常,那麼isnumber :regex : trycatch = 446 : 68 : 1

要沒有異常,那麼isnumber : trycatch :regex = 7 : 4 : 1

但無論如何,自己寫的函式始終是最快的。

劍指offer之字串是否為數值

這是 劍指offer 上的一道題,剛開始覺得這是一道挺簡單的題目,後來發現自己太年輕了,考慮的因素太少了,思考了而是分鐘還是無從下手,看了作者的思路深深被他折服了,題目如下 請實現乙個函式用來判斷字串是否表示數值 包括整數和小數 例如,字串 100 5e2 123 3.1415 以及 1e 16 都...

判斷字串是否表示數值

日色慾盡花含菸,月明欲素愁不眠。李白 長相思 其二 要點 判斷字串是不是數字 author jan on 2018 7 29.version 1.0 public class solution9 catch numberformatexception e return true 表示裡面的內容只有乙...

判斷字串是否表示數值

題目描述 請實現乙個函式用來判斷字串是否表示數值 包括整數和小數 例如,字串 100 5e2 123 3.1416 和 1e 16 都表示數值。但是 12e 1a3.14 1.2.3 5 和 12e 4.3 都不是。思路 找到通用規律a.b e e c a.b表示整數加小數,c表示指數,abc可能為...