0

in the program, i have to handle a input table like this.

a:1
b:2
c:3
?:6
#:14  

obviously, delimiter is ":" and "\n"

however, input like this will catch an exception

::2

I want to make ':' store into a char list as well.

how do i modify these code? and where should I put try-catch in?

String[] str;
str = textbox.Text.Trim().Split(':', '\n');

for (i = 0; i < str.Length; i = i + 2){
    char tempC;
    float tempFreq;

    if (char.TryParse(str[i], out tempC))
        c.Add(tempC);

    if (float.TryParse(str[i + 1], out tempFreq))
        freq.Add(tempFreq);

}
jay369
  • 1
  • "Split and keep delimiters in result" is quite common question - if your goal is different please make sure clearly specify what is special about your case in new question. – Alexei Levenkov May 18 '14 at 22:28

2 Answers2

0

First you need to parse your text line by line.Use the Lines property for that

Then you can just check if the current line starts with :

var lines = textbox.Lines;

foreach(var line in lines)
{
    if(line.StartsWith(':')) 
    { 
        c.Add(':');
        float tempFreq;
        if (float.TryParse(line.Split(':').Last(), out tempFreq))
             freq.Add(tempFreq);
    }
    else
    {
       char tempC;
       float tempFreq;
       string[] parts = line.Split(':');
       if (char.TryParse(parts[0], out tempC))
           c.Add(tempC);

       if (float.TryParse(parts[1], out tempFreq))
          freq.Add(tempFreq);
    } 
}

Btw, I assumed it is WinForms, Lines property might not exist in WPF, if that is the case just split the text by newline character first, then iterate over the lines and do the same things.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

You can use String.Split with StringSplitOptions.RemoveEmptyEntries, you can also split the lines first.

Your sample data with edge cases

var text = @"a:1
b:2
c:3
?:6
::2
#:14  ";

LINQ query which selects the char and the float as pair:

float freq = 0;
string[] lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var lineTokens = lines.Select(l => l.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries))
    .Where(arr => arr.Length == 2 && arr[0].Trim().Length == 1 && float.TryParse(arr[1].Trim(), out freq))
    .Select(arr => new { chr = arr[0].Trim()[0], freq });

Output:

foreach(var x in lineTokens)
    Console.WriteLine("Char:{0} Frequency:{1}", x.chr, x.freq);

Char:a Frequency:1
Char:b Frequency:2
Char:c Frequency:3
Char:? Frequency:6
Char:# Frequency:14
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939