简体   繁体   中英

Text file line by line into string array

I need help, trying to take a large text document ~1000 lines and put it into a string array, line by line.

Example:

string[] s = {firstLineHere, Secondline, etc};

I also want a way to find the first word, only the first word of the line, and once first word it found, copy the entire line. Find only the first word or each line!

There is an inbuilt method to achieve your requirement.

string[] lines = System.IO.File.ReadAllLines(@"C:\sample.txt");

If you want to read the file line by line

List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(@"C:\sample.txt"))
{
    while (reader.Peek() >= 0)
    {
        string line = reader.ReadLine();
        //Add your conditional logic to add the line to an array
        if (line.Contains(searchTerm)) {
            lines.Add(line);
        }
    }
}

You can accomplish this with File.ReadAllLines combined with a little Linq (to accomplish the addition to the question stated in the comments of Praveen's answer.

string[] identifiers = { /*Your identifiers for needed lines*/ };

string[] allLines = File.ReadAllLines("C:\test.txt");

string[] neededLines = allLines.Where(c => identifiers.Contains(c.SubString(0, c.IndexOf(' ') - 1))).ToArray();

Or make it more of a one liner:

string[] lines = File.ReadAllLines("your path").Where(c => identifiers.Contains(c.SubString(0, c.IndexOf(' ') - 1))).ToArray();

This will give you array of all the lines in your document that start with the keywords you define within your identifiers string array.

Another option you could use would be to read each individual line, while splitting the line into segments and comparing only the first element against the provided search term. I have provided a complete working demonstration below:

Solution:

class Program
{
    static void Main(string[] args)
    {
        // Get all lines that start with a given word from a file
        var result = GetLinesWithWord("The", "temp.txt");

        // Display the results.
        foreach (var line in result)
        {
            Console.WriteLine(line + "\r");
        }

        Console.ReadLine();
    }

    public static List<string> GetLinesWithWord(string word, string filename)
    {
        List<string> result = new List<string>(); // A list of strings where the first word of each is the provided search term.

        // Create a stream reader object to read a text file.
        using (StreamReader reader = new StreamReader(filename))
        {
            string line = string.Empty; // Contains a single line returned by the stream reader object.

            // While there are lines in the file, read a line into the line variable.
            while ((line = reader.ReadLine()) != null)
            {
                // If the line is white space, then there are no words to compare against, so move to next line.
                if (line != string.Empty)
                {
                    // Split the line into parts by a white space delimiter.
                    var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    // Get only the first word element of the line, trim off any additional white space
                    // and convert the it to lowercase. Compare the word element to the search term provided.
                    // If they are the same, add the line to the results list.
                    if (parts.Length > 0)
                    {
                        if (parts[0].ToLower().Trim() == word.ToLower().Trim())
                        {
                            result.Add(line);
                        }
                    }
                }
            }
        }

        return result;
    }
}

Where the sample text file may contain:

How shall I know thee in the sphere which keeps
The disembodied spirits of the dead,
When all of thee that time could wither sleeps
And perishes among the dust we tread?

For I shall feel the sting of ceaseless pain
If there I meet thy gentle presence not;
Nor hear the voice I love, nor read again
In thy serenest eyes the tender thought.

Will not thy own meek heart demand me there?
That heart whose fondest throbs to me were given?
My name on earth was ever in thy prayer,
Shall it be banished from thy tongue in heaven?

In meadows fanned by heaven's life-breathing wind,
In the resplendence of that glorious sphere,
And larger movements of the unfettered mind,
Wilt thou forget the love that joined us here?

The love that lived through all the stormy past,
And meekly with my harsher nature bore,
And deeper grew, and tenderer to the last,
Shall it expire with life, and be no more?

A happier lot than mine, and larger light,
Await thee there; for thou hast bowed thy will
In cheerful homage to the rule of right,
And lovest all, and renderest good for ill.

For me, the sordid cares in which I dwell,
Shrink and consume my heart, as heat the scroll;
And wrath has left its scar--that fire of hell
Has left its frightful scar upon my soul.

Yet though thou wear'st the glory of the sky,
Wilt thou not keep the same beloved name,
The same fair thoughtful brow, and gentle eye,
Lovelier in heaven's sweet climate, yet the same?

Shalt thou not teach me, in that calmer home,
The wisdom that I learned so ill in this--
The wisdom which is love--till I become
Thy fit companion in that land of bliss?

And you wanted to retrieve every line where the first word of the line is the word 'the' by calling the method like so:

var result = GetLinesWithWord("The", "temp.txt");

Your result should then be the following:

The disembodied spirits of the dead,
The love that lived through all the stormy past,
The same fair thoughtful brow, and gentle eye,
The wisdom that I learned so ill in this--
The wisdom which is love--till I become

Hopefully this answers your question adequately enough.

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