LPTSTR in;
// ...
std::wstring wstr(in);
boost::replace_all(wstr, "in", ",");
wcscpy(in, wstr.data());还有任何其他方法可以替换LPTSTR的值
在代码中,LPTSTR是一个wchar_t*
发布于 2021-10-25 23:58:36
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修改字符串文字本身将失败,但这将分配一个数组,并从字符串文字初始化它,然后修改该数组的内容。修改数组也没问题。
发布于 2021-10-26 02:08:22
当且仅当替换字符串的长度小于/等于搜索字符串时,才可以直接修改输入字符串的内容。
但是,如果替换字符串的长度大于搜索字符串的长度,则必须分配一个更大的新字符串,并根据需要将所需的字符复制到其中。
尝试如下所示:
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('\0');
}
}
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('\0');
delete[] in;
// or whatever the caller uses to free 'in'...
in = out;
}
}明白为什么使用原始C风格的字符串指针比使用C++风格的字符串类难得多了吧?
https://stackoverflow.com/questions/69715892
复制相似问题