I am using Stream Writer class and am trying to sum up all the numbers in my text file. My text file format is below:
name | number
-------------
a 2
a 3
What I am trying to do is to print out the sum of the numbers but am struggling to grab the numbers. I was thinking about using a for loop to sum up the numbers but not sure where to start to grab the numbers only.
You can simply do something like the following:
string[] lines = File.ReadAllLines("sample.txt");
int sum = 0;
foreach (string line in lines.Skip(2))
{
sum += Convert.ToInt32(line.Trim().Split(' ').Last());
}
sum
variable of type int
(if this needs to be double
it can be easily swapped here, of course).Skip(2)
skips the first two lines (header and line separator). Trim()
removes leading or trailing spaces from the current line. Split(' ')
splits the current line by a space character to break apart the name
column from the number
column (note that it actually creates additional empty columns as well because we split by a single space character). Last()
to selects the last column, which in this case will always select the number
column. Convert.ToInt32()
converts the last column to an int
type (which can be double
instead if desired, as explained previously).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.