如何替换LPTSTR的值?


LPTSTR in;
// ...
std::wstring wstr(in);
boost::replace_all(wstr, "in", ",");
wcscpy(in, wstr.data());

是否有其他方法来替换LPTSTR的值?

代码中,LPTSTRwchar_t*

LPTSTR就是wchar_t *。在本例中,您试图替换它所指向的数据中的某些内容。

要做到这一点,您需要确保它指向可修改的数据。在用字面量初始化它的常见情况下,这是行不通的:
LPCTSTR foo = "Foo";
LPTSTR mFoo = (LPTSTR)"Foo";
*foo = 'a'; // won't compile
*mFoo = 'a'; // crash and burn

要使其可修改,您可以(一种可能性)将其初始化为指向正确类型的数组的开头:

wchar_t buffer[256] = L"Foo";
LPTSTR foo = buffer;
*foo = 'a';  // no problem

修改字符串字面值本身将失败,但这将分配一个数组,并从字符串字面值初始化it,然后修改该数组的内容。修改数组是可以的。

当且仅当替换字符串小于或等于搜索字符串的长度,则可以直接修改输入字符串的内容。

但是,如果替换字符串的长度大于搜索字符串,那么您将不得不分配一个更大的新字符串,并根据需要将您想要的字符复制到其中。

试试这样写:

LPTSTR in = ...;
...
const int in_len = _tcslen(in);
LPTSTR in_end = in + in_len;
LPCTSTR search = ...; // _T("in")
const int search_len = _tcslen(search);
LPCTSTR replace = ...; // _T(",")
const int replace_len = _tcslen(replace);
LPTSTR p_in = _tcsstr(in, search);
if (replace_len < search_len)
{
if (p_in != NULL)
{
const int diff = search_len - replace_len;
do
{
memcpy(p_in, replace, replace_len * sizeof(TCHAR));
p_in += replace_len;
LPTSTR remaining = p_in + diff;
memmove(found, remaining, (in_end - remaining) * sizeof(TCHAR));
in_end -= diff;
}
while ((p_in = _tcsstr(p_in, search)) != NULL);
*in_end = _T('');
}
}
else if (replace_len == search_len)
{
while (p_in != NULL)
{
memcpy(p_in, replace, replace_len * sizeof(TCHAR));
p_in = _tcsstr(p_in + replace_len, search);
}
}
else
{
int numFound = 0;
while (p_in != NULL)
{
++numFound;
p_in = _tcsstr(p_in + search_len, search);
}
if (numFound > 0)
{
const out_len = in_len - (numFound * search_len) + (numFound * replace_len);
LPTSTR out = new TCHAR[out_len + 1];
// or whatever the caller used to allocate 'in', since
// the caller will need to free the new string later...
LPTSTR p_out = out, found;
p_in = in;
while ((found = _tcsstr(p_in, search)) != NULL)
{
if (found != p_in)
{
int tmp_len = found - p_in;
memcpy(p_out, p_in, tmp_len * sizeof(TCHAR));
p_out += tmp_len;
}
memcpy(p_out, replace, replace_len * sizeof(TCHAR));
p_out += replace_len;
p_in = found + search_len;
}
if (p_in < in_end)
{
int tmp_len = in_end - p_in;
memcpy(p_out, p_in, tmp_len * sizeof(TCHAR));
p_out += tmp_len;
}
*p_out = _T('');
delete[] in;
// or whatever the caller uses to free 'in'...
in = out;
}
}

明白为什么使用原始C风格的字符串指针比使用c++风格的字符串类要困难得多了吧?

相关内容

  • 没有找到相关文章