0

I want to trim string in c++/cx and I am using Platform::String

Platform::String myString = "  answer "
Mahesh
  • 143
  • 2
  • 16

1 Answers1

2

Platform::String is a wrapper around the Windows Runtime HSTRING type, which is immutable. You should ideally use Platform::String only in the public interfaces of Windows Runtime Components, which require it, but otherwise consider std::wstring for operations that modify the string such as trimming.

As documentation states:

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. It's easy and efficient to convert between wstring or wchar_t* and Platform::String.

You could use the following code to convert from Platform::String to wstring, then trim and then convert create new Platform::String from the result:

Platform::String^ myString = ref new Platform::String(L"  answer ");
//convert to wstring
std::wstring classicString(myString->Data());

//trimming
classicString.erase(0, classicString.find_first_not_of(' '));
classicString.erase(classicString.find_last_not_of(' ') + 1);

//convert to Platform::String
Platform::String^ modifiedString = ref new Platform::String(classicString.c_str());

For more involved solutions to trimming a wstring refer to this SO post.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91