0

I want to check szDir in szSelectedDir. I want the function to consider the below inputs are different. My sample function is not handling the scenario, please let me know the good solutions.

string szSelectedDir ="C:\\Windows1\Test";
string szDir="C:\\Windows";

void IsWindowsDirectory(const string szSpecialPath, const string szSelectedPath)
{

    if(szSelectedPath.compare(szSpecialPath) == 0)
    {
        printf("Both paths are same ");

    }
    else if(szSelectedPath.find(szSpecialPath) != string::npos)
    {
        printf("Both paths are same ");
    }
    else
    {
        printf("Both paths are different ");

    }

}
Vlad
  • 18,195
  • 4
  • 41
  • 71
Ullan
  • 1,311
  • 8
  • 21
  • 34
  • 2
    `if (szSelectedPath == szSpecialPath)` yay for operators! – AJG85 Jan 31 '12 at 19:15
  • I assume the `string` class you're using is actually `std::string` and you have a `using std::string;` somewhere at the top of your code file? – Cody Gray - on strike Jan 31 '12 at 19:16
  • The problem is underspecified. What kinds of paths would you consider identical? For the record, Windows filesystem is case-insensitive. – Seva Alekseyev Jan 31 '12 at 19:17
  • 3
    Also, this is so completely wrong on a level beyond the code. There is absolutely **no** guarantee that the Windows directory will be named `Windows`, much less that it will reside on the `C:` drive. Hard-coding paths is a huge no-no, and this detection method is doomed to fail. Call the [`GetWindowsDirectory` function](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724454.aspx) and skip the comparison altogether. – Cody Gray - on strike Jan 31 '12 at 19:18
  • Inputs: string szSelectedDir ="C:\\Windows\Test"; string szDir="C:\\Windows Expected Results: szSelectedDir contains szDir Inputs: string szSelectedDir ="C:\\WindowsTest\Test"; string szDir="C:\\Windows Expected Results: szSelectedDir contains szDir, but path is different, so I want to ignore this. – Ullan Jan 31 '12 at 19:19
  • The windows path I will find by using windows API. – Ullan Jan 31 '12 at 19:20
  • 1
    Checking whether one string contains another is obviously the wrong approach, as your counter-example shows. – Ben Voigt Jan 31 '12 at 19:47

1 Answers1

0

To check szDir in szSelectedDir.

if (szSelectedDir.find(szDir) != string::npos)
{
    // You found szDir in szSelectedDir
}

As someone already said, comparing strings in C++ is pretty straightforward...

if (szSelectedPath == szSpecialPath)

I suggest you to pass strings by reference (strings not null, amongst other things).

Six
  • 31
  • 4
  • Note passing objects by `const&` is generally to avoid the cost of a copy and to prevent changing the original object via the reference. While `const` by value as OP currently is doing is rather odd only pointers can be null. – AJG85 Jan 31 '12 at 19:48