user896692
user896692

Reputation: 2371

C# textfile parsing error

I´ve got a textfile, where every line is separated with \n an every value in a row is separated by \t.

StreamReader sr = new StreamReader(dlg.FileName);
String ganzes = sr.ReadToEnd();
String[] allezeilen = ganzes.Split('\n');
string[] ssa = allezeilen[i].Split('\t');
foreach (string h in ssa)
{
   String verwendungszw = h.Contains("Verwendungszweck");
}

Now, in the foreach loop, I try to find the entry in ssa that contains "Verwendungszweck". Ok, that is easy. But I don´t need the entry with "Verwendungszweck" in it, I need the next one.

How can I get the next entry?

Upvotes: 0

Views: 127

Answers (4)

GameAlchemist
GameAlchemist

Reputation: 19294

Note that you don't define what is 'i'

StreamReader sr = new StreamReader(dlg.FileName);
String ganzes = sr.ReadToEnd();
String[] allezeilen = ganzes.Split('\n');
foreach (string CurrentLine in allezeilen)
  {
     string[] ssa = CurrentLine.Split('\t');
     for (CurrentRowIndex=0, CurrentRowIndex<ssa.Count, CurrentRowIndex++)
         {
           if ssa[CurrentRowIndex].Contains("Verwendungszweck")
                   verwendungszw =ssa[++CurrentRowIndex] ; // or add it to a list and maybe exit for 
         }
  }

Upvotes: 0

D Stanley
D Stanley

Reputation: 152491

Answer without bounds checking and verification that the search string is in the array:

int pos = Array.IndexOf(ssa, "Verwendungszweck");
string value = ssa[pos + 1];

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

One option would be to use LINQ:

string value = ssa.SkipWhile(x => !x.Contains("Verwendungszweck"))
                  .ElementAtOrDefault(1);

That's probably the simplest way to do it if that's all you need. value will be null if no elements of ssa contained Verwendungszweck, or if only the last element did.

Upvotes: 5

Krzysztof
Krzysztof

Reputation: 16130

Change loop to

for (int i = 0; i < ssa.Length; i++) { 
    if (ssa[i].Contains("Verwendungszweck")) {
        String verwendungszw = ssa[i+1];
    }
}

Upvotes: 1

Related Questions