当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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.

网友答案:

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"
分享给朋友:
您可能感兴趣的文章:
随机阅读: