3

What would be most efficient way to compare QString and char*

if( mystring == mycharstar ) {} will perform malloc,

and

if(strcmp(mystring.toLocal8Bit().constData(),mycharstar ) == 0) {}

Will allocate a QByteArray

I would like to not have any allocation happening, would would you guys recommend?

What about

if(mystring == QLatin1String(mycharstar))

Would it be any better?

tux3
  • 7,171
  • 6
  • 39
  • 51
xchg.ca
  • 1,154
  • 2
  • 15
  • 28

2 Answers2

5

There is no "efficient" way that only uses casts. This is because QtString internally uses 16 bits to encode a single character while C strings use only 8 bits. That means any comparison based on memory pointers will simply almost always return false.

That's why you have to encode the 16 bit wide characters of QtString to the same encoding as your C string and that always needs at least one call to malloc().

See also: How to convert QString to std::string?

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
2

It could be if( mystring == QLatin1String(mycharstar) ), as suggested here.

Michał Leon
  • 2,108
  • 1
  • 15
  • 15