0

I read the *.txt file from c# and displayed in the console.

My text file looks like a table.

diwas      hey
ivonne     how
pokhara    d kd
lekhanath  when
dipisha    dalli hos
dfsa       sasf

Now I want to search for a string "pokhara" and if it is found then it should display the "d kd" and if not found display "Not found"

What I tried?

string[] lines = System.IO.ReadAllLines(@"C:\readme.txt");
foreach(string line in lines)
{
    string [] words = line.Split();
    foreach(string word in words)
    {
        if (word=="pokhara")
        {
            Console.WriteLine("Match Found");
        }
    }
}

My Problem: Match was found but how to display the next word of the line. Also sometimes in second row some words are split in two with a space, I need to show both words.

3
  • What is the delimiter in the text-fil? Commented May 4, 2015 at 8:25
  • @TimSchmelter I don't have a delimiter. I guess those spaces could be a delimiter. Commented May 4, 2015 at 8:34
  • there is a overload for .Split that can handle this - try to find it ;) Commented May 4, 2015 at 8:35

2 Answers 2

2

I guess your delimiter is the tab-character, then you can use String.Split and LINQ:

var lineFields = System.IO.File.ReadLines(@"C:\readme.txt")
    .Select(l => l.Split('\t'));
var matches = lineFields
    .Where(arr => arr.First().Trim() == "pokhara")
    .Select(arr => arr.Last().Trim());
// if you just want the first match:
string result = matches.FirstOrDefault();  // is null if not found

If you don't know the delimiter as suggested by your comment you have a problem. If you don't even know the rules of how the fields are separated it's very likely that your code is incorrect. So first determine the business logic, ask the people who created the text file. Then use the correct delimiter in String.Split.

If it's a space you can either use string.Split()(without argument), that includes spaces, tabs and new-line characters or use string.Split(' ') which only includes the space. But note that is a bad delimiter if the fields can contain spaces as well. Then either use a different or wrap the fields in quoting characters like "text with spaces". But then i suggest a real text-parser like the Microsoft.VisualBasic.FileIO.TextFieldParser which can also be used in C#. It has a HasFieldsEnclosedInQuotes property.

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

4 Comments

and if not found display "Not found" - .DefaultIfEmpty("Not found").First()
@fubo: with DefaultIfEmpty you don't need FirstOrDefault but you can use First safely.
@TimSchmelter yeap tab is a delimiter. If tab is a delimiter than I need to again split each line with three spaces. and if the first array is equal to the string I was searching than need to display the second array of the same line. Thanks
@Lifestohack: either the tab-character is the delimiter or three spaces. I guess y the spaces are actually a tab. But if you really need to split by three spaces you can use string.Split(new[]{" "}, String.SplitOptions.None). The rest of the code can remain unchanged. If you want you could change arr.Last() to arr[1] to take the second field. But that causes an exception on a line which only contains one field.
0

This works ...

  string[] lines = System.IO.ReadAllLines(@"C:\readme.txt");
    string stringTobeDisplayed = string.Empty;
    foreach(string line in lines)
    {
        stringTobeDisplayed = string.Empty;
        string [] words = line.Split();
         //I assume that the first word in every line is the key word to be found
          if (word[0].Trim()=="pokhara")
            {
                Console.WriteLine("Match Found");

                for(int i=1 ; i < words.Length ; i++)
                 {
                     stringTobeDisplayed += words[i]
                 }

                 Console.WriteLine(stringTobeDisplayed);

            }

    }

Comments

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.