String.at() for wchar_t UNICODE string in Win32 and appending wchar_t character to a string

thebluetropics 1,046 Reputation points
2022-10-08T02:13:36.82+00:00

1. I need a helper function (if possible, win32 built-in functions) that capable of getting the character at the specified index.
For example (in pseudocode):

   wchar_t text0[] = L"example";  
   wchar_t character0 = charAtW(text0, 1); // 'x'  
     
   wchar_t text1[] = L"お元気ですか?"  
   wchar_t character1 = charAtW(text1, 2); // '気'  

2. I also need a helper function that can append single wchar_t to the end of the string.
For example (in pseudocode):

   wchar_t text[] = L"brus";  
   wchar_t character = L'h';  
     
   charAppendW(text, character);  
     
   OutputDebugStringW(text); // Outputs "brush"  

The helper function described above can be either destructive or non-destructive (modify the existing one or return the new modified string)

I really need your help,
Regards, @thebluetropics

Windows development Windows API - Win32
Developer technologies C++
{count} votes

Accepted answer
  1. Barry Schwarz 3,746 Reputation points
    2022-10-08T05:18:07.017+00:00

    For you first requirement, why not simply use the [ ] operator?

        wchar_t character0 = text0[1]; // 'x'  
        wchar_t character1 = text1[2]; // '気'  
      
    

    Your second requirement cannot be satisfied as written. text has enough room for exactly 5 wchar_t: L'b', L'r', L'u', L's', and L'\0'. While it is possible for you replace the last character with the L'h', the result is no longer a string because it is not terminated properly. Attempting to process it as a string will cause undefined behavior.

    If you change the definition of text to allow extra space, such as text[10], there will be room to add the new character and move the terminator over one. Your helper function could look something like

    void my_concatenate(whar_t *dest, wchar_t letter)  
    {  
       static wchar*t my_str[2]; // initialized by virtue of static  
       my_str[0] = letter;  
       wcscat(dest, my_str);  
       return;  
    }  
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.