Search code examples
c++cwchar-t

Get the last token out of wchar_t*


I have a wchar_t* in my C code, that contains URL in the following format:

https://example.com/test/...../abcde12345

I want to split it by the slashes, and get only the last token (in that example, I want to get a new wchar_t* that contains "abcde12345").

How can I do it?

Thank you?


Solution

  • In C, you can use wcsrchr to find the last occurence of /:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <wchar.h>
    int main(void){
      wchar_t *some_string = L"abc/def/ghi";
    
      wchar_t *last_token = NULL;
      wchar_t *temp = wcsrchr(some_string, L'/');
      if(temp){
        temp++;
        last_token = malloc((wcslen(temp) + 1) * sizeof(wchar_t));
        wcscpy(last_token, temp);
      }
    
      if(last_token){
        wprintf(L"Last token: %s", last_token);
      }else{
        wprintf(L"No / found");
      }
    }