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.

8
  • You can do this by writing the correct code do this, then compiling and executing it. Commented Mar 20, 2016 at 12:41
  • 1
    Better to use std::wstring. Commented Mar 20, 2016 at 12:57
  • 1
    If you want a non-constant wchar_t* then you can pass &text[0] like: winfunc(&text[0], text.size()); Commented Mar 20, 2016 at 13:05
  • 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. Commented Mar 20, 2016 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). Commented Mar 20, 2016 at 13:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I updated my question. Sorry for the typo. wchar_t is array in my case. Am I still can not replace this way?
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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.