2017-04-10 112 views
-1

編輯: 代碼應該沒問題...是上游代碼問題。C++用另一個wstring替換wstring(長度超過80個字符)

謝謝大家!

原題:

我發現了一個代碼示例從

Replace part of a string with another string

而且我做了一些改變(編輯):

bool replace(std::wstring& str, const std::wstring& from, const std::wstring& to) { 
size_t start_pos = str.find(from); 
if (start_pos == std::wstring::npos) 
    return false; 
str.replace(start_pos, from.length(), to); 
return true; 
} 

// Source wstring 
// (This is an example, actual wstring is return by a code library) 
wstring inputString = L"The apple is a deciduous tree, \\ngenerally standing 1.8 to 4.6 m (6 to 15 ft) tall in cultivation \\nand up to 12 m (39 ft) in the wild." 
// Place some conditions 
wstring textToReplace = L"\\n"; 
wstring newWstring = L"\n"; 

replace(inputString, textToReplace, newWstring); 

而且它在開始正常工作。但是當我生成一個包含135個字符的字符串時,結果只返回前79個字符。

例如,這是我的wstring:

The apple is a deciduous tree, \\ngenerally standing 1.8 to 4.6 m (6 to 15 ft) tall in cultivation \\nand up to 12 m (39 ft) in the wild. 

我想在源代碼替換 「\\ n」 增加 「\ n」。所以我可以只打印一行(wcout)。

,這就是我的了:

The apple is a deciduous tree, \ngenerally standing 1.8 to 4.6 m (6 to 15 ft) 

我要的是:

The apple is a deciduous tree, \ngenerally standing 1.8 to 4.6 m (6 to 15 ft) tall in cultivation \nand up to 12 m (39 ft) in the wild. 

編輯: 我知道我應該把while循環,我做之前,但不保存。

如果wstring小於80的長度,它完全工作。

「\\ n」實際上被替換爲「\ n」,並且沒有問題與cout < <。

但我不明白最後57個字符是怎麼回事。

他們已經走了。我如何更換的wstring的一部分,與其他的wstring,

但源wstring的是超過80個字符「長」?

+4

請提供[mcve]。你如何檢查結果?爲什麼標題中提到wstring,當代碼中有字符串? – Angew

+0

請注意,您的解決方案不會循環。只有任何'from'標籤的第一個實例將被替換。 –

+0

謝謝,夥計們,我更新了這個問題...問題的關鍵部分應該是爲什麼角色在79之後不復存在。在我做了一段時間循環之前,它也是在80後丟失的。 @Angew –

回答

0

通過檢查inputString.size()值,

由代碼庫返回的wstring的是總是79的長度。

這是一個上游代碼庫問題... 感謝你們所有人!