2017-04-10 116 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的长度。

这是一个上游代码库问题... 感谢你们所有人!