1 /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2  * Use of this file is governed by the BSD 3-clause license that
3  * can be found in the LICENSE.txt file in the project root.
4  */
5 
6 #include "support/StringUtils.h"
7 
8 namespace antlrcpp {
9 
replaceAll(std::string & str,std::string const & from,std::string const & to)10 void replaceAll(std::string& str, std::string const& from, std::string const& to)
11 {
12   if (from.empty())
13     return;
14 
15   size_t start_pos = 0;
16   while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
17     str.replace(start_pos, from.length(), to);
18     start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'.
19   }
20 }
21 
ws2s(std::wstring const & wstr)22 std::string ws2s(std::wstring const& wstr) {
23 #ifndef USE_UTF8_INSTEAD_OF_CODECVT
24   std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
25   std::string narrow = converter.to_bytes(wstr);
26 #else
27   std::string narrow;
28   utf8::utf32to8(wstr.begin(), wstr.end(), std::back_inserter(narrow));
29 #endif
30 
31   return narrow;
32 }
33 
s2ws(const std::string & str)34 std::wstring s2ws(const std::string &str) {
35 #ifndef USE_UTF8_INSTEAD_OF_CODECVT
36   std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
37   std::wstring wide = converter.from_bytes(str);
38 #else
39   std::wstring wide;
40   utf8::utf8to32(str.begin(), str.end(), std::back_inserter(wide));
41 #endif
42 
43   return wide;
44 }
45 
46 } // namespace antrlcpp
47