Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading string each number c#

Tags:

c#

list

suppose this is my txt file:

line1
line2
line3
line4
line5

im reading content of this file with:

 string line;
List<string> stdList = new List<string>();

StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{                
    stdList.Add(line);           
}
finally
{//need help here
}

Now i want to read data in stdList, but read only value every 2 line(in this case i've to read "line2" and "line4"). can anyone put me in the right way?

like image 230
devilkkw Avatar asked Aug 01 '12 16:08

devilkkw


People also ask

How can read a string in C?

Read String from the user You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

How do I return the number of characters in a string in C?

Use the strlen() function provided by the C standard library string. h header file. char name[7] = "Flavio"; strlen(name); This function will return the length of a string as an integer value.

How do we read a multi word string in C?

Explanation: The function gets() is used for collecting a string of characters terminated by new line from the standard input stream stdin. Therefore gets() is more appropriate for reading a multi-word string.

Can strings store numbers in C?

The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.


2 Answers

Even shorter than Yuck's approach and it doesn't need to read the whole file into memory in one go :)

var list = File.ReadLines(filename)
               .Where((ignored, index) => index % 2 == 1)
               .ToList();

Admittedly it does require .NET 4. The key part is the overload of Where which provides the index as well as the value for the predicate to act on. We don't really care about the value (which is why I've named the parameter ignored) - we just want odd indexes. Obviously we care about the value when we build the list, but that's fine - it's only ignored for the predicate.

like image 68
Jon Skeet Avatar answered Oct 22 '22 12:10

Jon Skeet


You can simplify your file read logic into one line, and just loop through every other line this way:

var lines = File.ReadAllLines(myFile);
for (var i = 1; i < lines.Length; i += 2) {
  // do something
}

EDIT: Starting at i = 1 which is line2 in your example.

like image 42
Yuck Avatar answered Oct 22 '22 14:10

Yuck