简体   繁体   中英

Split a string of Number and characters

I had a List liRoom which contains a alphanumeric and Alphabetic string For Example

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

This List is of type Alphanumeric and Alphabetic so i want to take the max numeric value from this list of string.
I had tried to do it this way

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.

And

 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.

But both shows error when st is Hall,Assembly
Help me How to do this.

there are few reasons you will get exception in your code. I'm adding few condition for those possible exceptions.

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();
 }

Please try the following:

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 
*/

You should add below in your code by checking whether match is success or not

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

You don't need foreach , it can be done with one statement:

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

It seems odd but it's working. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM