简体   繁体   中英

How to extract a substring from a PWSTR in C++

I'm currently modifying a credential provider for Windows 7, in C++. The Windows SDK requires use of PWSTR.

I've hit a problem where the username is sometimes being passed as DOMAIN\\username and sometimes as domain.tld\\username and sometimes just username. What I'd like to do is extract the username from this, and only take the substring after the slash.

I'm new to C++ and none of the string functions appear to work with PWSTR. I've tried a few conversions to wchar_t* but it's still not getting me anywhere.

How can this be achieved?

TIA

You could do something like:

PWSTR GetUserName(PWSTR pszUser)
{
   PWSTR pszLastSlash = wcsrchr(pszUser, L'\\');
   return pszLastSlash ? pszLastSlash + 1 : pszUser;
}

Note this doesn't do a separate memory allocation - the thing you return is the pointer to the part of the string beginning after the last slash. If you were to do a proper "substring" operation like you might see in higher-level objects (instead of just taking len - i starting at offset i ) you'd have to do a copy (or somehow track that you're only considering a smaller length).

Don't use std::string for wide-character strings. Use std::wstring instead. PWSTR is a wchar_t * , and where std::string is std::basic_string<char> , std::wstring is std::basic_string<wchar_t> . Using that, you should be able to accomplish what you could converting a char * to std::string and manipulating it. You can see that both are similar and have the same functions etc. on this page .

From there, all that needs to be done is something like the following:

wchar_t chars[] = L"abc";
std::wstring ws = chars;
std::wstring sub = ws.substr (0, 2); 
std::wcout << sub.c_str(); //should print 'ab'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM