字符串比较C ++

时间:2012-01-31 19:13:15

标签: c++

我想在szDir中查看szSelectedDir。我希望函数考虑下面的输入是不同的。我的示例函数没有处理方案,请让我知道好的解决方案。

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 ");

    }

}

1 个答案:

答案 0 :(得分:0)

要检查szDir中的szSelectedDir

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

正如有人已经说过的,比较C ++中的字符串非常简单......

if (szSelectedPath == szSpecialPath)

我建议你通过引用传递字符串(字符串不是null,等等)。