0

How can I replace string in a wchar_t variable?

wchar_t text[] = L"Start Notepad.exe";

I want to replace Notepad.exe with Word.exe.

John Sewell
  • 874
  • 8
  • 18
  • You can do this by writing the correct code do this, then compiling and executing it. – Sam Varshavchik Mar 20 '16 at 12:41
  • 1
    Better to use `std::wstring`. – Galik Mar 20 '16 at 12:57
  • @Galik Thanks but, Windows expects `wchar_t` for most of its functions and it is really pain to convert from `wstring` to `wchar_t`. That is why I try to use `wchar_t`. Even `wstring.c_str()` does not help because sometimes VS requires it to be not a `constant`. What do you recommend? – John Sewell Mar 20 '16 at 12:59
  • 1
    If you want a non-constant `wchar_t*` then you can pass `&text[0]` like: `winfunc(&text[0], text.size());` – Galik Mar 20 '16 at 13:05
  • @Galik thanks again. But would there be any issues when using `&text[0]` ? Because I am dealing with international characters for localization. Not sure if passing first pointer cause any `utf16` character loss? Is not there any standard way for dealing with `wchar_t`? – John Sewell Mar 20 '16 at 13:11
  • 1
    There is no difference passing `&text[0]` and passing the address of a `wchar_t` array. In fact the `std::wstring` class is basically just a wrapper around a dynamic `wchar_t*` array. – Galik Mar 20 '16 at 13:17
  • 1
    You won't even lose any performance because `std::wstring` methods are trivial, inlined and calling them is optimized away by the compiler. Its just as fast as an array (because that's what it is). – Galik Mar 20 '16 at 13:27
  • see [Modifying underlying char array of a c++ string object](https://stackoverflow.com/q/5729203/995714) – phuclv Mar 31 '19 at 10:41

2 Answers2

2

wchar_t is just one character, not the string. In your case you need std::wstring, string consisting of wchar_t. Here is answer on how to replace one substring with another.

Community
  • 1
  • 1
CodeFuller
  • 30,317
  • 3
  • 63
  • 79
0

Basically you need to use a pointer or index variable and replace the characters one by one and end with the null character.

Here is an example, (note that C++ programmers might hate this code, but is fairly acceptable for C programmers...):

wchar_t lpSrcText[] = L"Start Notepad.exe";
wchar_t const * lpReplace = L"Word.exe";

int i = 0;
while(*(lpReplace + i))
{
     lpSrcText[6 + i] = *(lpReplace + i);
     i++;
}
*(lpReplace + i) = L'\0';
E_net4
  • 27,810
  • 13
  • 101
  • 139
yoel halb
  • 12,188
  • 3
  • 57
  • 52