4

I have a file. Each line looks like the following:

[00000] 0xD176234F81150469: foo

What I am attempting to do is, if a line contains a certain substring, I want to extract everything on the right of the substring found. For instance, if I were searching for 0xD176234F81150469: in the above line, it would return foo. Each string is of variable length. I am using C#.

As a note, every line in the file looks like the above, having a base-16 number enclosed in square brackets on the left, followed by a hexadecimal hash and a semicolon, and an english string afterwards.

How could I go about this?

Edit

Here is my code:

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 box = new Form1();
        if(MessageBox.Show("This process may take a little while as we loop through all the books.", "Confirm?", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
        {
            XDocument doc = XDocument.Load(@"C:\Users\****\Desktop\books.xml");

            var Titles = doc.Descendants("Title");

            List<string> list = new List<string>();

            foreach(var Title in Titles)
            {
                string searchstr = Title.Parent.Name.ToString();
                string val = Title.Value;
                string has = @"Gameplay/Excel/Books/" + searchstr + @":" + val;
                ulong hash = FNV64.GetHash(has);
                var hash2 = string.Format("0x{0:X}", hash);

                list.Add(val + " (" + hash2 + ")");
                // Sample output: "foo (0xD176234F81150469)"
            }

            string[] books = list.ToArray();

            File.WriteAllLines(@"C:\Users\****\Desktop\books.txt", books);
        }
        else
        {
            MessageBox.Show("Aborted.", "Aborted");
        }
    }

I also iterated through every line of the file, adding it to a list<>. I must've accidentally deleted this when trying the suggestions. Also, I am very new to C#. The main thing I am getting stumped on is the matching.

3
  • 1
    Well, which bit is causing you difficulties? Taking the substring? Finding matching lines? Iterating over the file line by line to start with?
    – Jon Skeet
    May 7, 2013 at 9:03
  • This generally is not a very hard operation to program. Can you show us your code and where you are stuck? And then we'll attempt to give you suggestions in the right direction.
    – Bazzz
    May 7, 2013 at 9:05
  • I've added more information to my original post.
    – Seabody
    May 7, 2013 at 9:24

4 Answers 4

4

You could use File.ReadLines and this Linq query:

string search = "0xD176234F81150469:";
IEnumerable<String> lines = File.ReadLines(path)
    .Select(l => new { Line = l, Index = l.IndexOf(search) })
    .Where(x => x.Index > -1)
    .Select(x => x.Line.Substring(x.Index + search.Length));

foreach (var line in lines)
    Console.WriteLine("Line: " + line);
1

This works if you don't want to use Linq query.

//"I also iterated through every line of the file, adding it to a list<>." Do this again.
List<string> li = new List<string>()

//However you create this string make sure you include the ":" at the end.
string searchStr = "0xD176234F81150469:"; 

private void button1_Click(object sender, EventArgs e)
{
    foreach (string line in li)
    {
        string[] words;
        words = line.Split(' '); //{"[00000]", "0xD176234F81150469:", "foo"}

        if (temp[1] == searchStr)
        {
            list.Add(temp[2] + " (" + temp[1] + ")");
            // Sample output: "foo (0xD176234F81150469)"
        }
    }
}
0
string file = ...
string search= ...
var result = File.ReadLines(file)
              .Where(line => line.Contains(search))
              .Select(line => line.Substring(
                                   line.IndexOf(search) + search.Length + 1);
0

Unfortunately, none of the other solutions worked for me. I was iterating through the hashes using foreach, so I would be iterating through all the items millions of times needlessly. In the end, I did this:

            using (StreamReader r = new StreamReader(@"C:\Users\****\Desktop\strings.txt"))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    lines++;
                    if (lines >= 6)
                    {
                        string[] bits = line.Split(':');

                        if(string.IsNullOrWhiteSpace(line))
                        {
                            continue;
                        }

                        try
                        {
                            strlist.Add(bits[0].Substring(10), bits[1]);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }

            foreach(var Title in Titles)
            {
                string searchstr = Title.Parent.Name.ToString();
                string val = Title.Value;
                string has = @"Gameplay/Excel/Books/" + searchstr + ":" + val;
                ulong hash = FNV64.GetHash(has);
                var hash2 = " " + string.Format("0x{0:X}", hash);

                try
                {
                    if (strlist.ContainsKey(hash2))
                    {
                        list.Add(strlist[hash2]);
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    continue;
                }
            }

This gave me the output I expected in a short period of time.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.