2015-09-12 32 views
1

給出的形式的陣列如何提取從C字符串++的整數數組

char* timePeriod= {"6AM#8AM","11AM#1PM","7AM#3PM","7AM#10AM","10AM#12PM"}; 

我怎樣可以提取的開始和結束時間在以下形式的整數數組:

start_time={6,11,7,7,10} 
end_time={8,1,3,10,12} 
+4

呃,日期解析檢測!使用日期解析庫,永遠不要自己動手! http://www.boost.org/doc/libs/1_42_0/doc/html/date_time/date_time_io.html – Dai

回答

1

您可以使用「sscanf」來做到這一點。不要忘記標記爲有用:)

#include <stdio.h> 
int main() 
{ 
    int a,b,i; 
    int start_time[5], end_time[5]; 

    char *t[5] = {"6AM#8AM","11AM#1PM","7AM#3PM","7AM#10AM","10AM#12PM"}; 
    char *(*ptr)[5] = &t; 

    for(i=0;i<5;i++) 
    { 
     sscanf((*ptr)[i], "%d%*[AP]M#%d%*[AP]M", &a, &b); 
     start_time[i]=a; 
     end_time[i]=b; 
    } 
    printf("Starting time : "); 
    for(i=0;i<5;i++) 
    { 
     printf("%d ",start_time[i]); 
    } 
    printf("\nEnding time : "); 
    for(i=0;i<5;i++) 
    { 
     printf("%d ",end_time[i]); 
    } 
    return 0; 
} 
OUTPUT: 
Starting time : 6 11 7 7 10 
Ending time : 8 1 3 10 12 
0

甲非常簡單的方法是使用strtok來分割#上的字符串,然後在每一塊上使用atoi。一旦它看到一個非數字值就會停止。

0

sscanf能夠做到這一點,雖然我不認爲這是一個很好的方法。看here的細節

#include <stdio.h> 
int main() { 
    const char* t = "6PM#8AM"; 
    int a, b; 
    sscanf(t, "%d%*[AP]M#%d%*[AP]M", &a, &b); 
    printf("%d %d\n", a, b); 
    return 0; 
} 

,或者你可以在regex C++ 11

#include <iostream> 
#include <regex> 
#include <string> 
using namespace std; 
int main() { 
    string t("6PM#8AM"); 
    smatch match; 
    regex re("([[:digit:]])+[AP]M#([[:digit:]])+[AP]M"); 
    if (regex_match(t, match, re)) { 
    cout << match[1].str() << " " << match[2].str() << '\n'; 
    } 
    return 0; 
} 
0

注:以下解決方案使一些非常具體的假設,你的數據集(如果這些都沒有的情況下,你可能更喜歡使用正則表達式)。

  1. 該字符串總是以整數開始
  2. 的endtimes總是要麼在你​​的字符串的第四或第五指數
  3. 零不是一個有效的時間

#include <iostream> 
#include <string> 

int main() { 

    std::string timePeriod[5] = {"6AM#8AM","11AM#1PM","7AM#3PM","7AM#10AM","10AM#12PM"}; 
    int startTimes[5] = {0,0,0,0,0}; 
    int  endTimes[5] = {0,0,0,0,0}; 

    for(int i=0;i<5;i++) { 

     std::string s = timePeriod[i]; 
     startTimes[i] = atoi(s.c_str());    // Convert first number to integer 
     endTimes[i] = atoi(s.substr(4).c_str()); // Convert 2nd numbers to integer 
     if(endTimes[i] == 0)       // If zero 
      endTimes[i] = atoi(s.substr(5).c_str()); // Get the 5th index instead 

     std::cout << "Start: " << startTimes[i] << "\t End: " << endTimes[i] << std::endl; 
    } 
} 

缺少前導零使得它有點棘手,但最終 - 它可以使用子串快速解決(假設你也不介意chang將char *轉換爲std :: string)。