如何在c ++中查找字符串是否为guid

时间:2011-02-14 13:51:18

标签: c++

如何在本机c ++中查找字符串是否为guid?代码示例将有很大帮助

5 个答案:

答案 0 :(得分:8)

如果您需要手工完成(来自wikipedia的信息):

  1. 检查长度(36,包括连字符)
  2. 检查连字符是否在预期位置(9-14-19-24)
  3. 检查所有其他字符是否为十六进制(isxdigit

答案 1 :(得分:3)

您可以使用正则表达式来查看它是否符合GUID格式。

答案 2 :(得分:2)

尝试以下代码 - 可以提供帮助。

_bstr_t sGuid( _T("guid to validate") );
GUID guid;

if( SUCCEEDED( ::CLSIDFromString( sGuid, &guid ) )
{
  // Guid string is valid
}

答案 3 :(得分:0)

这是一个更快的原生 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[9] != '-' || s[14] != '-' ||
        s[19] != '-' || s[24] != '-')
        return false;

   for (int i = 0; i < s.length(); i++) {
       if (i == 9 || i == 14 || i == 19 || i == 24) 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);
}

答案 4 :(得分:-1)

这是一个代码示例,以防您还需要一个: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!
}