Войти

Показать полную графическую версию : [решено] строковой парсинг


Surround
10-03-2008, 19:31
нужно на C# сделать парсинг строки вида 123-126,130 в массив 123,124..126,130, желателно как можно более универсально...

podsyp
16-03-2008, 20:37
Здравствуйте.

Возможно такой код (с тесирующим примером) вас устроит. Удачи.

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

}

Surround
17-03-2008, 16:51
спасибо за идею!
я же реализовал это так:

//------разбирает форматированную строку в массив
private void ParseInt(string ids)
{
list_id = new List<int>();
//ids вида:[12-15,24-29,40]
string[] SplFirst;
string[] SplSecond;
SplFirst = ids.Split(',');//получили массив SplFirst вида: [12-15];[24-29];[40]
foreach (string f in SplFirst)
{
SplSecond = f.Split('-');//здесь массив SplSecond принимает значения: [12];[15] затем [24];[29] затем [40]
if (SplSecond.Length > 1)//то есть получили парный элемент (12-15)
{
int a = Convert.ToInt32(SplSecond[0]);//начало диапазона
int b = Convert.ToInt32(SplSecond[1]);//его конец
if (a > b)//a > b - то просто поменяем их местами
{
int buf = b;
b = a;
a = buf;
}
for (int i = a; i <= b; i++)
{
list_id.Add(i);//добавлем новый элемент в список
}
}
else//если элемент одиночный - то просто добавляем его
{
int c = Convert.ToInt32(SplSecond[0]);
list_id.Add(c);
}
}
//для отладки
/*foreach (int n in list_id)
{
MessageBox.Show(n.ToString());
}*/
}




© OSzone.net 2001-2012