【问题标题】:Get the last token out of wchar_t* [closed]从 wchar_t* 中获取最后一个令牌 [关闭]
【发布时间】:2021-12-15 13:50:06
【问题描述】:

我的 C 代码中有一个 wchar_t*,它包含以下格式的 URL:

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

我想用斜杠分割它,并且只获取最后一个标记(在该示例中,我想获取一个包含“abcde12345”的新 wchar_t*)。

我该怎么做?

谢谢?

【问题讨论】:

  • 首先,选择一种语言并删除不适用的标签。那么,您发现了哪些函数可以用于该语言中的字符串处理?

标签: c++ c wchar-t


【解决方案1】:

在 C 语言中,您可以使用 wcsrchr 查找 / 的最后一次出现:

#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");
  }
}

【讨论】:

    【解决方案2】:

    只需使用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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2021-12-06
      • 2019-12-19
      • 2021-04-30
      相关资源
      最近更新 更多