0

I have const wchar_t* looks like "\n\t\t\t\tsomething\n\t\t\t\t" and I want to get "something". What is the most efficient way to do it?

[EDIT] I've worked out something like this:

typedef wchar_t XMLCh

const XMLCh* trimTabs(const XMLCh* text)
{
string dest = XMLString::transcode(text);
dest.erase(remove(dest.begin(),dest.end(),'\t'), dest.end());
dest.erase(remove(dest.begin(),dest.end(),'\n'), dest.end());
return XMLStr(dest.c_str()).getXMLStr();
}

XMLStr class which is existing already in my project helped mi a lot. I hope it's good answer. XMLString is a class from Xercesc library.

Adek
  • 43
  • 1
  • 7

2 Answers2

0

Copy your const wchar_t* to std::wstring, and then trim it using one of the methods from What's the best way to trim std::string?. You cant trim const wchar_t*, it must be copied.

[edit]

additional comment to your updated question. With below function signature it is not possible to accomplish what you want.

const XMLCh* trimTabs(const XMLCh* text)

I dont know how the rest of your code looks like, but here the best you can do is to change to:

string trimTabs(const XMLCh* text)
{
string dest = XMLString::transcode(text);
dest.erase(remove(dest.begin(),dest.end(),'\t'), dest.end());
dest.erase(remove(dest.begin(),dest.end(),'\n'), dest.end());
return string(XMLStr(dest.c_str()).getXMLStr());
}

otherwise you are returning const wchar_t* to some temporary buffer which is undefined behaviur. I assume here your XMLStr is not managing memory in some global allocator.

Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100
0

You will need new variable to store the characters, so first of all just iterate over your string and find the first and the last occurrance of non-whitespace character. You can use two pointers and iterate from the beginning and the end of a string. Then you can use this function to copy the string:

wchar_t* wcscpy (wchar_t* destination, const wchar_t* source);

You can find the description here: C++ Reference - wcscpy

Mateusz Kleinert
  • 1,316
  • 11
  • 20