-2

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?

alon
  • 57
  • 1
  • 1
  • 6
  • 9
    First, pick a language and remove the tag that doesn't apply. Then, what functions have you found for string handling in that language? – Ulrich Eckhardt Oct 31 '21 at 11:59

2 Answers2

0

Just use std::wstring.

int main()
{
    std::wstring input = L"https://example.com/test/...../abcde12345";

    auto separatorPos = input.rfind(L'/');
    if (separatorPos == std::wstring::npos)
    {
        std::cout << "separator not found\n";
    }
    else
    {
        auto suffix = input.substr(separatorPos + 1);
        std::wcout << suffix << L'\n';
    }

    return 0;
}
fabian
  • 80,457
  • 12
  • 86
  • 114
0

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");
  }
}
lulle2007200
  • 888
  • 9
  • 20