簡體   English   中英

拆分一串數字和字符

[英]Split a string of Number and characters

我有一個列表liRoom,其中包含字母數字和字母字符串

List<string> liRoom = new List<string>() {"Room1","Room2","Room3",  
                                         "Room4","Hall","Room5","Assembly",  
                                         "Room6","Room7","Room8","Room9};

此列表的類型為字母數字和字母,因此我想從此字符串列表中獲取最大數值。
我試過這樣做

var ss = new Regex("(?<Alpha>[a-zA-Z]+)(?<Numeric>[0-9]+)");  
List<int> liNumeric = new List<int>();  
foreach (string st in liRoom)  
{   
var varMatch = ss.Match(st);  
liNumeric.Add(Convert.ToInt16(varMatch.Groups["Numeric"].Value));   
}  
int MaxValue = liNumeric.Max();// Result Must be 9 from above Example.

 List<int> liNumeric = new List<int>();  
 foreach (string st in liRoom)  
 {   
   liNumeric.Add( int.Parse(new string(st.Where(char.IsDigit).ToArray())));   
 }  
 int MaxValue = liNumeric.Max();// Result Must be 9 from above Example.

但是當stHall,Assembly時都顯示錯誤
幫幫我怎么做

您的代碼中出現異常的原因很少。 我為這些可能的例外情況添加了一些條件。

List<int> liNumeric = new List<int>();  
 foreach (string st in liRoom)  
 { 
   // int.Parse will fail if you don't have any digit in the input 
   if(st.Any(char.IsDigit))
   {
       liNumeric.Add(int.Parse(new string(st.Where(char.IsDigit).ToArray()))); 
   }

 }  
 if (liNumeric.Any()) //Max will fail if you don't have items in the liNumeric
 {
     int MaxValue = liNumeric.Max();
 }

請嘗試以下方法:

List<string> liRoom = new List<string>() {"Room1","Room2","Room3",  
                                         "Room4","Hall","Room5","Assembly",  
                                         "Room6","Room7","Room8","Room9"};


var re = new Regex(@"\d+");

int max = liRoom.Select(_ => re.Match(_))
                .Where(_ => _.Success)
                .Max( _ => int.Parse(_.Value));

/* 
   max = 9 
*/

您應通過檢查匹配是否成功,在代碼中添加以下內容

if (varMatch.Success)
{
     liNumeric.Add(Convert.ToInt16(varMatch.Groups["Numeric"].Value));
}

您不需要foreach ,只需執行以下語句即可:

int value = liRoom.Where(x => x.Any(char.IsDigit))
            .Select(x => Convert.ToInt32(new String(x.Where(char.IsDigit).ToArray())))
            .Max();

看起來很奇怪,但是可以正常工作。 :)

暫無
暫無

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

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