Reputation: 371
How can I access an individual character in Platform::String^
?
I am using this variable type because it appears to be the only way to write a string to a TextBlock
on a Universal Windows App.
I have tried the following methods to get individual characters to no avail:
String ^ str = "string";
std::string::iterator it = str->begin(); //Error: platform string has no member "begin"
std::string::iterator it = str.begin(); //Error: expression must have a class type
str[0] = 't' /*Error: expression must have a pointer-to-object or handle-to-C++/CX
mapping-array type*/
I am putting the String^ in a text block named "textBlock" as follows: textBlock->Text = str;
I am open to approaches other than modifying the Platform::String
. My only requirement is that the string ends in a form that can be put into a TextBox
Upvotes: 0
Views: 666
Reputation: 166
An addition to the already supplied answer: you are also able to change a Platform::String^ into a std::wstring so you can modify it, then you can always change it back to Platform::String^
Platform::String^ str = "string";
wstring orig (str->Data());
orig[0] = L't';
str = ref new Platform::String(orig.c_str());
Upvotes: 0
Reputation: 51395
Platform::String represents a sequential collection of Unicode characters that is used to represent text. The controlled sequence is immutable: Once constructed, the contents of a Platform::String
can no longer be modified.
If you need a modifiable string, the canonical solution is to use another string class, and convert to/from Platform::String
when calling the Windows Runtime, or receiving string data. This is explained under Strings (C++/CX):
The Platform::String Class provides methods for several common string operations, but it's not designed to be a full-featured string class. In your C++ module, use standard C++ string types such as wstring for any significant text processing, and then convert the final result to Platform::String^ before you pass it to or from a public interface.
You could rewrite your code sample as follows:
// Use a standard C++ string as long as you need to modify it
std::wstring s = L"string";
s[0] = L't'; // Replace first character
// Convert to Platform::String^ when required
Platform::String^ ps = ref new Platform::String(s.c_str(), s.length());
Upvotes: 2