简体   繁体   中英

How can I change array elements C#

How can I get array or array values from for-loop?

Example first outputs prints right solution, but second output prints just last line, last word of array.

How to get correct value for array from splitLine and save it in variable for using it later?

File text

Title:

Here is my first line.
Here is my second line.
Here is my third line.
Here is my fourth line.
Here is my fifth line.

Code

using System;
using System.IO;

namespace Array
{
    class Class
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"file.txt");

            string[] array = new string[] {};

            for (int i = 0; i < lines.Length; i++)
            {
                string[] splitLine = lines[i].Split();
                for (int j = 0; j < splitLine.Length; j++)
                {
                    Console.WriteLine(splitLine[j]);
                    array = splitLine[j].Split();
                }
            }
            Array.ForEach(array, Console.WriteLine);
        }
    }
}

If you are expecting the 'array' variable to accumulated values from each string split operations, then you don't have it quite right. As written your code only sets the 'array' variable to the last string split operations. You should consider using a collection type like List as the type for your array. Then call the Add method to add a single item or the AddRange method to add an enumeration (which can be an array).

The ReadAllLines() method is already splitting your text into lines. I'm not clear if you want to split it further? If not, simply:

var lines = File.ReadAllLines(@"file.txt");
lines.ToList().ForEach(Console.WriteLine);

Should output the lines to the console

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM