bengosha
bengosha

Reputation: 81

C# How to comparing two string?

I want to comparison two string. First is from the dateTimePicker, and second is from file.

string firtsdate = dateTimePicker1.Value.ToString("yyyy-MM-dd");  
string seconddate = dateTimePicker2.Value.ToString("yyyy-MM-dd"); 

string FilePath = path;

string fileContent = File.ReadAllText(FilePath);
string[] integerStrings = fileContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

int count = 0;

for (int n = 0; n < integerStrings.Length;)            
{
    count = integerStrings[n].Length;               
    //Console.Write(count + "\n");
    count--;                                         
    if (count > 2)                                  
    {
        string datastart;
        string dataend;

        if (integerStrings[n] == firtsdate)
        {
            datastart = integerStrings[n];
            Console.Write(datastart);
            dataend = (DateTime.Parse(datastart).AddDays(1)).ToShortDateString();
            Console.Write(dataend + "\n");
        }
        else
        {
            n = n + 7;
        }
    }
}

File looks like this:

Problem is that they do not want to compare two of the same value, like 2016-07-02 == 2016-07-02 (from file).

Upvotes: 0

Views: 339

Answers (2)

Nam Tran
Nam Tran

Reputation: 661

If you are sure about your date time format, and strings are correct, you can compare 2 strings by Equals, or Compare. The end of line character in linux is \n (line feed) and windows is \r (carriage return), and \r\n for both, so you should split line by these characters or read file line by line.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

I suspect this is the problem:

string fileContent = File.ReadAllText(FilePath);
string[] integerStrings = fileContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

A line break on Windows is "\r\n" - so each line in your split will end in a \r. The simplest way to fix this is to just replace those two lines with:

string[] integerStrings = File.ReadAllLines(FilePath);

Upvotes: 3

Related Questions