【发布时间】:2011-06-26 22:45:30
【问题描述】:
如何在原生 c++ 中查找字符串是否为 guid?一个代码示例会有很大帮助
【问题讨论】:
-
我不会 c++ 但你不能用这个:msdn.microsoft.com/en-us/library/system.guid.tryparse.aspx
标签: c++
如何在原生 c++ 中查找字符串是否为 guid?一个代码示例会有很大帮助
【问题讨论】:
标签: c++
您可以使用正则表达式来查看它是否符合 GUID 格式。
【讨论】:
试试下面的代码 - 会有所帮助。
_bstr_t sGuid( _T("guid to validate") );
GUID guid;
if( SUCCEEDED( ::CLSIDFromString( sGuid, &guid ) )
{
// Guid string is valid
}
【讨论】:
这是一个更快的原生 C++ 版本,没有正则表达式或类似 scanf() 的调用。
#include <cctype>
#include <string>
using namespace std;
bool isCanonicalUUID(const string &s) {
// Does it match the format 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'?
if (s.length() != 36) return false;
if (s[8] != '-' || s[13] != '-' ||
s[18] != '-' || s[23] != '-')
return false;
for (int i = 0; i < s.length(); i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) continue;
if (isspace(s[i])) return false;
if (!isxdigit(s[i])) return true;
}
return true;
}
bool isMicrosoftUUID(const string &s) {
// Does it match the format '{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?
if (s.length() != 38) return false;
if (s[0] != '{' || s[37] != '}') return false;
if (s[10] != '-' || s[15] != '-' ||
s[20] != '-' || s[25] != '-')
return false;
for (int i = 1; i < s.length()-1; i++) {
if (i == 10 || i == 15 || i == 20 || i == 25) continue;
if (isspace(s[i])) return false;
if (!isxdigit(s[i])) return true;
}
return true;
}
bool isUUID(const string &s) {
return isCannonicalUUID(s) || isMicrosoftUUID(s);
}
【讨论】:
此方法利用 scanf 解析器,也适用于纯 C:
#include <stdio.h>
#include <string.h>
int validateUUID(const char *candidate)
{
int tmp;
const char *s = candidate;
while (*s)
if (isspace(*s++))
return 0;
return s - candidate == 36
&& sscanf(candidate, "%4x%4x-%4x-%4x-%4x-%4x%4x%4x%c",
&tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp) == 8;
}
用例如测试:
int main(int argc, char *argv[])
{
if (argc > 1)
puts(validateUUID(argv[1]) ? "OK" : "Invalid");
}
【讨论】:
这是一个代码示例,以防您仍然需要一个:P
#include <ctype.h>
using namespace std;
bool isUUID(string uuid)
{
/*
* Check if the provided uuid is valid.
* 1. The length of uuids should always be 36.
* 2. Hyphens are expected at positions {9, 14, 19, 24}.
* 3. The rest characters should be simple xdigits.
*/
int hyphens[4] = {9, 14, 19, 24};
if (uuid.length() != 36)
{
return false;//Oops. The lenth doesn't match.
}
for (int i = 0, counter = 0; i < 36; i ++)
{
char var = uuid[i];
if (i == hyphens[counter] - 1)// Check if a hyphen is expected here.
{
// Yep. We need a hyphen here.
if (var != '-')
{
return false;// Oops. The character is not a hyphen.
}
else
{
counter++;// Move on to the next expected hyphen position.
}
}
else
{
// Nope. The character here should be a simple xdigit
if (isxdigit(var) == false)
{
return false;// Oops. The current character is not a hyphen.
}
}
}
return true;// Seen'em all!
}
【讨论】: