user2325553
user2325553

Reputation: 23

How can i select a specific element from a string?

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        string linie;
        foreach (string elem in Directory.GetFiles(@"C:\Users\A\Desktop\FIles", "*.txt"))
        {
            Console.WriteLine(elem);
            StreamReader reader = new StreamReader(elem);
            {
                while (!reader.EndOfStream)
                {
                    linie=reader.ReadLine();
                    Console.WriteLine(linie);                         
                }
            }
            reader.Close();

        }
        Console.ReadKey();
        Console.WriteLine(DateTime.ParseExact("5/10/2005", "m/d/yyyy", null).Day);
    }
}

What i need is to select only the Date from a file.
For example if i have the string "the date is 20/2/2012" in a .txt file, i need to substract only 20/2/2012 and to compare it with the current date.

Upvotes: 2

Views: 92

Answers (1)

phadaphunk
phadaphunk

Reputation: 13283

If you want an easy lazy solution, you can always add a : and Split on it. (You could split on white spaces but then I would have to count for the index and I don't want to do this).

string   dateFromFile = "The date is : 20/2/2012";
string[] dateString =  dateFromFile.Split(':');

string myDate = dateString[1];

Ok I looked at my answer and decided I was too lazy...

string dateFromFile = "The date is 20/2/2012";
string[] dateString = dateFromFile.Split(' ');

string myDate = dateString[3];

It splits the string everytime it sees the sepcified character and returns a String[].

In the second example (where I split on white space, the array would look like this)

dateString[0] = "The"
dateString[1] = "date"
dateString[2] = "is"
dateString[3] = "20/2/2012"

Upvotes: 2

Related Questions