1

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!

4
  • 2
    System.IO.File.ReadAllLines() its not line by line, but otherwise should do the job Commented Apr 22, 2015 at 21:11
  • @PraveenPaulose, realized it just after I posted and removed the comment. Commented Apr 22, 2015 at 21:14
  • 1
    Can you give more information on why you think ~1000 lines is a large document? Are those lines extraordinarily long? Commented Apr 22, 2015 at 21:21
  • @Mare Infinitus this is the largest text file I've worked with before Commented Apr 22, 2015 at 21:23

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);
        }
    }
}

6 Comments

that way wouldn't work with my search, Im trying to find the first word and once found, put the rest of the line into a string. is there any other way?
@The_Reich: Then you should write a question that describes what you need. This is very bad form.
@The_Reich Please update your question to accurately state what you're trying to do, otherwise you won't get the answers you need.
@The_Reich: Added an iterative method
@PraveenPaulose Sorry, this is the first post I've ever made. Ca you please look at the updated question. I need to search for the first word only of each line. Otherwise I will get tons of results.
|
0

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.

5 Comments

What is the way to call this @James Shaw, It doesn't seem to return any words when I set "word" to a word I want to find!
@The_Reich I have updated the solution I provided in order to make it more clear. To test it, replace your existing program class with the one above. Please let me know if you need any further help.
@The_Reich Always a pleasure. If the answer has helped you solve your problem. Could you be so kind as to accept it as the answer?
I went in and check your edits. It works, but I had to add if (parts.Length > 0) {
Yes I originally had that condition but replaced the condition with the check to determine if the line is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.