![]() |
строковой парсинг
нужно на C# сделать парсинг строки вида 123-126,130 в массив 123,124..126,130, желателно как можно более универсально...
|
Здравствуйте.
Возможно такой код (с тесирующим примером) вас устроит. Удачи. using System; namespace ConsoleApplication5 { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { string test_str = "123-126,130"; StringParser parser = new StringParser(test_str); Console.WriteLine("123-126,130"); foreach(int my_int in parser.Ints) { Console.Write(my_int.ToString()+","); } Console.WriteLine(); Console.Read(); } } class StringParser { public System.Collections.ArrayList Ints; public StringParser(string str) { Ints = new System.Collections.ArrayList(); string cur_str = ""; int pos = 0; try { while(pos != -1) { pos = GetNext(ref cur_str, str, pos); AppendList(ref Ints, cur_str); } } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } private int GetNext(ref string str_out, string str, int pos) { int idx = str.IndexOf(",",pos+1); if(idx!=-1) { str_out = str.Substring(pos,idx-pos); } else { if(pos<str.Length-1) { str_out = str.Substring(pos+1); } else { str_out = ""; } } return idx; } private void AppendList(ref System.Collections.ArrayList int_nums, string str_nums) { int first_int = 0; int not_empty_pos = 0; while(str_nums[not_empty_pos] == ' ') { not_empty_pos++; } int minus_pos = str_nums.IndexOf("-"); if(minus_pos!=-1) { string first_int_str = str_nums.Substring(not_empty_pos,minus_pos-not_empty_pos); string second_int_str = str_nums.Substring(minus_pos+1,str_nums.Length - minus_pos-1); first_int = int.Parse(first_int_str); int second_int = int.Parse(second_int_str); if(second_int <= first_int) throw new Exception("Wrong format"); for(int i = first_int; i<=second_int;i++ ) { int_nums.Add(i); } } else { first_int = int.Parse(str_nums); int_nums.Add(first_int); } } } } |
спасибо за идею!
я же реализовал это так: Код:
//------разбирает форматированную строку в массив |
Время: 05:58. |
Время: 05:58.
© OSzone.net 2001-