前言:
在Text 組件中,如果內(nèi)容為數(shù)字時,需要獲取該文本的數(shù)字時,一般是先把文本字符串轉換為整型再輸出。
把文本中的內(nèi)容輸出為字符串用string 類型, 輸出為整型用int類型。這個相信大家都知道。如果你需要當文本內(nèi)容為字符串時,輸出字符串類型,當文本內(nèi)容為數(shù)字時,輸出整型。那么就需要判斷當前文本內(nèi)容是否為數(shù)字。再決定輸出類型。
注:如果文本字符串中不是數(shù)字,卻又強行轉為整型時會報異常。
異常:FormatException: Input string was not in the correct format。
判斷字符串是否為數(shù)字 通過正則表達式,實現(xiàn)是比較方便的:
Regex.IsMatch(str, @"^\d+$"); // 判斷字符串是否為數(shù)字 的正則表達式1
這里需要 頭文件引用:
using System.Text.RegularExpressions;
具體方法實現(xiàn)參考:
public Text test;
string str = test.text;
int num = 0;
if(isNumber(str)){
num = int.Parse(str);
Debug.Log("\n === 文本內(nèi)容為數(shù)字 ===:"+ num);
}else {
Debug.Log("\n === 文本內(nèi)容為字符串 ===:"+ str);
}
// 判斷 字符串是否為數(shù)字方法
public static bool isNumber(string str)
{
bool isMatch = Regex.IsMatch(str, @"^\d+$"); // 判斷字符串是否為數(shù)字 的正則表達式
return isMatch;
}
相關教程:
C#判斷輸入文字是否是數(shù)字[
3]
http://26638.oa22.cn
該文章在 2024/10/14 17:42:52 編輯過