2013-11-26 28 views
0

我想分割點上的實際key,然後在點上分割後提取所有的字段。如何分割點上的字符串並有效地提取所有字段?

我的鑰匙看起來像這樣的東西 -

t26.example.1136580077.colox 

目前,我可以拆分它的第一個點後,僅提取第一場是t26。現在我不知道如何提取所有其他領域,以及使用下面的代碼更像是C.

以下是我目前使用的代碼從中提取第一個字段。

if (key) 
{ 
    char* first_dot = strchr(key, '.'); 
    if (first_dot) 
    { 
     // cut at the first '.' character 
     first_dot[0] = 0; 
    } 
} 

cout << "Fist Key: " << key << endl; 

在點分裂後。我的第一場將是string在這種情況下是t26,第二場也將string在這種情況下是example,第三字段將爲uint64_t在這種情況下是1136580077和第四場也將串在這種情況下是colox

任何想法如何有效地做到這一點?與istringstream相比,使用strtok更有效嗎?

+0

使用strtok的是更有效 –

+0

@AliKazmi,只是好奇,爲什麼會這樣呢? – AKIWEB

+0

strtok是基於c的函數,在C#中討論Split函數,它代表用戶調用strtok,所以你不直接調用strtok並保存一些執行時間? –

回答

1
#include <stdint.h> 
#include <vector> 
#include <iostream> 
#include <stdlib.h> 
#include <string.h> 
using namespace std; 

vector<string> spilt(char str[]) 
{ 
    vector<string> res; 
    char* p; 
    char* totken = strtok_s(str, ".", &p); 
    while(totken != NULL) 
    { 
     res.push_back(totken); 
     totken = strtok_s(NULL, ".", &p); 
    } 
    return res; 
} 

int main() 
{ 
    char str[] = "t26.example.1136580077.colox"; 
    vector<string> res = spilt(str); 
    string field1 = res[0]; 
    string field2 = res[1]; 
    uint64_t field3 = atoi(res[2].c_str()); 
    string field4 = res[3]; 

    cout<<field1<<" "<<field2<<" "<<field3<<" "<<field4<<endl; 
} 
+0

沒有使用while循環有什麼辦法來提取所有東西,以便我可以將個別值放入其數據類型中? – AKIWEB

+0

我認爲你不能。 Mybe你應該使用一些正則表達式庫。 – BlackMamba

+0

我明白了......如果我們需要使用while循環,那麼如何在我的問題中顯示如何將各個字段值置於其對應的數據類型中? – AKIWEB

0

編寫一個函數,用於分割字符串並限定鍵的組成部分。考慮到您對效率的關注,請使用strchr來定位點和條形以提取組件值,其中strncpy的長度由指針delta確定。

下面是一些未經測試的僞代碼:

const int MAX_COMP_SIZE = 256; 

int count = 0; 
const char *p = key; 

if (p != NULL) 
{ 
    char comp[MAX_COMP_SIZE]; 
    const int CompSize = sizeof(comp)/sizeof(comp[0]); 

    while (*p != '\0') 
    { 
     const char *q = strchr(p, '.'); 

     if (q != NULL) 
     { 
      int len = q - p; 

      if (len >= CompSize) 
       return -1; 

      strncpy(comp, p, q-p)[len] = '\0'; 
     } 
     else 
     { 
      if (strlen(p) >= CompSize) 
       return -1; 

      strcpy(comp, p); 
     } 

     // store/verify key components based on index, count 
     // implement in separate function 
     switch(count) 
     { 
      case 0: ... 
      case 1: ... 
      default: return -1; 
     } 

     count++ 

     if (q == NULL) 
      break; 

     q++; // skip dot 

     p = q; // setup next 

    } 

} 

if (count < REQUIRED_KEY_COMPONENTS) 
    return -1;