SFML community forums

Help => General => Topic started by: e_barroga on September 02, 2009, 03:09:25 am

Title: Compare two sf::String
Post by: e_barroga on September 02, 2009, 03:09:25 am
I've tried the following to no avail:
Code: [Select]

sf::String strCompare("text");
if (myText.GetText() == strCompare.GetText())
{
    ...
}
Title: Compare two sf::String
Post by: e_barroga on September 02, 2009, 05:41:55 am
Nevermind, solved by casting the sf::String to a std::string then comparing with a string literal:
Code: [Select]

if (static_cast<std::string>(myString.GetText()) == "String to compare.")
{
    ...
}
Title: Compare two sf::String
Post by: christoph on September 02, 2009, 09:52:31 am
std::strcmp() from <cstring> would have solved that quite as well
Title: Compare two sf::String
Post by: Hiura on September 02, 2009, 07:01:56 pm
Quote from: "christoph"
std::strcmp() from <cstring> would have solved that quite as well
Yes. Or you can do :
Code: [Select]
if (std::string(myString.GetText()) == "String to compare.") This last one is my favorite.
Title: Compare two sf::String
Post by: christoph on September 02, 2009, 10:54:03 pm
Quote from: "Hiura"
Yes. Or you can do :
Code: [Select]
if (std::string(myString.GetText()) == "String to compare.") This last one is my favorite.


Well there's not much (if any) difference in the working of this compared to the static_case and == for strings quite likely just calls strcmp() on the c_str() parts again so casting to string is likely to be a waste of resources ;)
Title: Compare two sf::String
Post by: Hiura on September 02, 2009, 11:19:44 pm
Quote
a waste of resources

Isn't it negligible ?  :wink:
Title: Compare two sf::String
Post by: Nexus on September 04, 2009, 05:05:44 pm
Quote from: "christoph"
Well there's not much (if any) difference in the working of this compared to the static_case and == for strings quite likely just calls strcmp() on the c_str() parts again so casting to string is likely to be a waste of resources ;)
And creating a temporary std::string on which you call c_str() is less waste of resources?

Very likely, the direct operator== comparison is as fast or even faster than the comparision of c-strings. For example, if the strings have different length, the evaluation can be done in O(1). On the contrary, strcmp() requires O(n) in every case. Besides, it is possible that a c_str() call implies additional operations like adding a null termination (std::string isn't required to store a null-terminated c-string).