比较c++中的两个字符串

Comparing two strings in c++

本文关键字:两个 字符串 c++ 比较      更新时间:2023-10-16

我在比较c++中的两个字符串时遇到了一个奇怪的问题。

c指向" dreaming ",我已经从printf语句中确认了这一点。现在我想把它和"梦幻"字符串进行比较,但是每次它都进入else部分并显示不匹配。

Str1和Str2的

cout语句也打印相同的输出"dream",但Str1的长度显示为7,Str2的长度显示为6。

谁能告诉我是什么问题以及如何解决它?

谢谢。

        char *c;
        c = strtok (temp,",");   
                    // Here   printf ("%sn",c);   prints    dreamy
        while (c != NULL)
        {
            std::string Str1 = std::string(c);
            std::string Str2 = std::string("dreamy");
            cout << "Str1  " << Str1 << "Len" << Str1.length() <<endl;  //  Len = 7 showing for  c = "dreamy"
            cout << "Str2  " << Str2 << "Len" << Str2.length() <<endl;  //  Len = 6 for "dreamy"
            if(Str1.compare(Str2) == 0)
            {
                cout << "Finally Match";
                presence[1] = 1;
            }
            else
                cout << " Dont Match";
            printf ("%sn",c);

Len = 7表示第一个字符串中有一个伪字符(可能是空格或换行符)。