2015-09-12 92 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)。