Try this:
At design-time:
1. put a Button, 'button1 on a Form
2. put two TextBoxes, 'textBox1, 'textBox2 on the same Form
3. psste the code below into the Form's .cs file
4. wire-up 'button1's Click Event Handler to 'button1_Click shown below
At run-time:
1. enter your test text into 'textBox1, click 'button1
2. examine the output in 'textBox2
The code:
private StringBuilder sb = new StringBuilder();
private string[] stringAry;
private string[] seriesStringAry;
private int iStart;
private int iEnd;
private void button1_Click(object sender, EventArgs e)
{
sb.Clear();
stringAry = textBox1.Text.Split(',');
foreach (string theString in stringAry)
{
theString.Trim();
if (theString.Contains("-"))
{
seriesStringAry = theString.Split('-');
if (seriesStringAry.Length != 2) throw new InvalidDataException("malformed sub-string in your source string");
iStart = Convert.ToInt32(seriesStringAry[0]);
iEnd = Convert.ToInt32(seriesStringAry[1]);
for (int i = iStart; i <= iEnd; i++)
{
sb.Append(i.ToString());
sb.Append("|");
}
}
else
{
sb.Append(theString);
sb.Append("|");
}
}
sb.Remove(sb.Length - 1, 1);
textBox2.Text = sb.ToString();
}
Discussion: This will work, but doesn't "feel like" elegant code :)
Note that the idea of assuming there is always a final "|" character here, and "knocking it off," is kind of a sloppy way of cleaning-up-after. For "production code," I (and I think you) should first: check there is a final "|," before knocking anything off. And, second, you can re-write the code to use a for-loop for the main loop, instead of foreach, in which case you can keep track of when you reach the final output of your processing, and, at that point, omit writing the "|" character. I was just lazy here, sorry.
What would happen if you wanted an entry in the text you were parsing to be in a form like this: "15-11" ? The code here would fail, in that case, but it would not be that difficult to re-write the code to handle that case.
Note, also, that the assumption here is: the strings in the data you parse
always represent integers.
Now, what would be really "elegant" would be to see one of CP's RegEx experts add an answer to this question using only RegEx !