Linda Harrison
Linda Harrison

Reputation: 257

Taking the last four characters of an charachter array

I have

TCHAR szPIDKEY[255];//for product id
 DWORD dwLen = sizeof(szPIDKEY)/sizeof(szPIDKEY[0]); //calculating the size of the key
UINT res = MsiGetProperty(hInstall, _T("PIDKEY"), szPIDKEY, &dwLen); 
if(res != ERROR_SUCCESS) 
{
    //fail the installation 
    return 1; 
}

the key string looks like xxxx-xxxx-xxxx-xxxx, i want to take only the last four xxxx in TCHAR , how to do this?

Thanks

Upvotes: 1

Views: 923

Answers (3)

jahhaj
jahhaj

Reputation: 3119

Is this really so hard?

TCHAR lastFour[5] /* 4 + 1 for null terminator */
_tcscpy(lastFour, szPIDKEY + dwLen - 4); /* copy the last four characters and 
                                        null terminator */

If you want to do strings the C way, then you are going to have to learn how to do pointer manipulations like the above. szPIDKEY is an array, but it also functions as a pointer to the first element of the array, szPIDKEY + dwLen is then a pointer to the last character of the key (the null terminator). So szPIDKEY + dwLen - 4 is a pointer to four characters before that.

Untested code.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

TCHAR is nothing else but a char if UNICODE is not defined and wchar if it is defined. So if you want to take the last 4 symbols you may treat is as you would have treated these types.

So maybe you should do something like:

#ifdef UNICODE
#include <wchar.h>
int get_len(TCHAR[] val) {
  return wcslen(val);
}
#else 
#include <cstring>
int get_len(TCHAR[] val) {
  return strlen(val);
}
#endif

EDIT: In fact there is a function already defined in windows that does what I described above and it is _tcslen (thanks to jajjaj for this one). However I decided to leave the code above so that you get the idea what it does.

And then using the function above you have the last 4 characters stored in

szPIDKEY[_tcslen(szPIDKEY-4)], ...szPIDKEY[_tcslen(szPIDKEY-1)]

Hope this helps.

Upvotes: 0

Jeeva
Jeeva

Reputation: 4663

 #ifndef UNICODE  
 typedef std::string String 
 #else
 typedef std::wstring String 
 #endif

String szKey = szPIDKEY;
size_t found = szKey.find_last_of("-");
String szFind = szKey.substr (found,4);

Upvotes: 2

Related Questions