Convert WTF::String to String and back to WTF::String?

524 views
Skip to first unread message

Ivan Hutomo

unread,
Nov 19, 2022, 2:36:27 AM11/19/22
to Chromium-dev
Hi everyone, I would to do operation in WTF::String like .substr and .find, is it possible to convert from WTF::String to String first then convert it back to WTF::String? Thank you

I am doing something like this for convert from WTF::String to String, but not sure it could work properly:


std::string url_string =  wtf_string.Utf8().data()

and from string to wtf string like below:

wtf_string = url_string.c_str()

Thank you for help.

Ian Clelland

unread,
Nov 19, 2022, 11:59:25 AM11/19/22
to hutom...@gmail.com, Chromium-dev
You can do that, and it will work to convert between types, but you're probably doing too much work. WTF::String::Utf8() already returns a std::string, so there's no need to call data() on that and then convert it back to std::string. Similarly, WTF::String has a constructor that takes a std::string, so you don't need to extract the c_str() in order to convert back.

Even less work, though, would be to just call the Substring and find/Find methods directly on WTF::String; you may not have a need to convert to std::string in the first place.

--
--
Chromium Developers mailing list: chromi...@chromium.org
View archives, change email options, or unsubscribe:
http://groups.google.com/a/chromium.org/group/chromium-dev
---
You received this message because you are subscribed to the Google Groups "Chromium-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-dev...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-dev/5c459319-9ab1-4c0e-a4e2-d8dd69a068cbn%40chromium.org.

Jeremy Roman

unread,
Nov 23, 2022, 12:13:54 PM11/23/22
to icle...@chromium.org, hutom...@gmail.com, Chromium-dev
On Sat, Nov 19, 2022 at 11:59 AM Ian Clelland <icle...@chromium.org> wrote:
You can do that, and it will work to convert between types, but you're probably doing too much work. WTF::String::Utf8() already returns a std::string, so there's no need to call data() on that and then convert it back to std::string. Similarly, WTF::String has a constructor that takes a std::string, so you don't need to extract the c_str() in order to convert back.

This constructor is unlikely to be what you want, though, since it assumes the input is ASCII or Latin-1, not UTF-8. String::FromUTF8(base::StringPiece) is the appropriate way to convert a UTF-8 string.

Note that conversion to and from UTF-8 is not a lossless operation.
 
Reply all
Reply to author
Forward
0 new messages