[英]extracting integer from string
這可能非常簡單但我有一個服務返回一個前面帶有零的數字的字符串。 零的計數是不可預測的,但我需要從值中提取數字。 值的長度也不是恆定的。 對於前者 00001234, 002345667, 0000000, 011, 00000987
- 在所有這些值中,我需要提取1234, 2345667, <no value>, 11, 987
。 我嘗試過以下代碼,但它也返回零:
string.Join( null,System.Text.RegularExpressions.Regex.Split( expr, "[^\\d]" ) );
有人可以幫忙嗎?
得到了我的答案::
我用stringObj.TrimStart('0')
得到它。 但我同意使用Int.Parse或Int.TryParse是一種更好的處理方式。 希望這對像我這樣的人有用!
int ret;
if (int.TryParse("0001234", out ret))
{
return ret.ToString();
}
throw new Exception("eep");
var numString = "00001234, 002345667, 0000000, 011, 00000987";
// result will contain "1234, 2345667, <no value>, 11, 987"
var result = string.Join(", ", numString.Split().Select(s =>
{
var intVal = int.Parse(s);
return intVal == 0 ? "<no value>" : intVal.ToString();
}));
轉換為整數並返回字符串?
int num = Convert.ToInt32(val);
string val = Convert.ToString(num);
這應該可以解決問題
string s = "0005";
string output = Convert.ToInt32(s.TrimStart(Convert.ToChar("0")));
正規表達的力量來救援!
static readonly Regex rx = new Regex( @"[^\d]*((0*)([1-9][0-9]*)?)" ) ;
public static IEnumerable<string> ParseNumbers( string s )
{
for ( Match matched = rx.Match(s) ; matched.Success ; matched = matched.NextMatch() )
{
if ( matched.Groups[1].Length > 0 )
{
yield return matched.Groups[3].Value ;
}
}
}
將字符串"00001234, 002345667, 0000000, 011, 00000987"
傳遞給ParseNumbers()
產生枚舉
干杯!
000000是0不為空....
int intInteger = -1;
int.tryparse(stringNumber,out intInteger);
應該給你一個干凈的整數。
您可以使用Int.Parse將字符串解析為整數。
String s = "00001234, 002345667, 0000000, 011, 00000987";
string[] nums= s.Split(',');
foreach (string num in nums
{
Console.WriteLine(Int.Parse(num)); //you'll need special handling to print "<no value>" when the string is 0000000
}
(實際上沒有編譯過這個)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.