簡體   English   中英

只從字符串中取出數字並放入數組中

[英]Take only numbers from string and put in an array

好的,我發現這是為了從字符串中刪除所有不是數字的“垃圾”

TextIN = " 0 . 1 ,2 ; 3 4 -5 6 ,7 ,8; 9 "

string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray());

=“0123456789”

這會從我的字符串中刪除所有“垃圾”,只留下數字,但我仍然可以修改它,所以我可以至少有一個分隔符,例如 a ', ' b 在我的數字之間,如 "0,1,2,3 ,4,5,6,7,8,9" 因為我需要分隔這個數字所以我可以把它們放在一個整數數組中並使用它們並且並不總是只有一個數字我可能有 105、85692 等.. 有什么幫助嗎?!

您還可以像這樣轉換為數值:

int[] numbers = Regex.Matches(textIN, "(-?[0-9]+)").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();

@LB:同意,但也可能有負值。

string test = string.Join(",", textIN.Where(Char.IsDigit));

對於 n 位數字,您可以使用正則表達式。

string s = String.Join(",",
                  Regex.Matches(textIN,@"\d+").Cast<Match>().Select(m=>m.Value));
string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray()); = "0123456789"
string[] words = justNumbers.Split(',');

將字符串分隔成一個數字數組,用逗號分隔。

暫無
暫無

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

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