LPTSTR in;
// ...
std::wstring wstr(in);
boost::replace_all(wstr, "in", ",");
wcscpy(in, wstr.data());
還有其他方法可以替換 a 的值LPTSTR嗎?
在代碼中,LPTSTR是一個wchar_t*
uj5u.com熱心網友回復:
AnLPTSTR只是一個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
修改字串文字本身會失敗,但這會分配一個陣列,并從字串文字初始化它,然后修改該陣列的內容。修改陣列很好。
uj5u.com熱心網友回復:
如果且僅當替換字串的長度小于/等于搜索字串,則您可以直接修改輸入字串的內容。
但是,如果替換字串的長度大于搜索字串的長度,則您必須分配一個更大的新字串,并根據需要將所需的字符復制到其中。
嘗試這樣的事情:
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://www.uj5u.com/net/338137.html
