2014-09-30 144 views
0

我正在編寫一個程序,將短日期(mm/dd/yyyy)轉換爲長日期(2014年3月12日)並打印出日期。如何搜索字符串中的字符?

程序有工作給予以下用戶輸入: 2014年10月23日 2014年9月25日 2015年12月8日 2016年1月1日

我有計劃與工作第一個用戶輸入,但我不知道如何處理在字符串的第一個位置沒有「0」的用戶輸入。

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    string date; 
    cout << "Enter a date (mm/dd/yyyy): " << endl; 
    getline(cin, date); 

    string month, day, year; 

    // Extract month, day, and year from date 
    month = date.substr(0, 2); 
    day = date.substr(3, 2); 
    year = date.substr(6, 4); 

    // Check what month it is 
    if (month == "01") { 
     month = "January"; 
    } 
    else if (month == "02") { 
     month = "February"; 
    } 
    else if (month == "03") { 
     month = "March"; 
    } 
    else if (month == "04") { 
     month = "April"; 
    } 
    else if (month == "05") { 
     month = "May"; 
    } 
    else if (month == "06") { 
     month = "June"; 
    } 
    else if (month == "07") { 
     month = "July"; 
    } 
    else if (month == "08") { 
     month = "August"; 
    } 
    else if (month == "09") { 
     month = "September"; 
    } 
    else if (month == "10") { 
     month = "October"; 
    } 
    else if (month == "11") { 
     month = "November"; 
    } 
    else { 
     month = "December"; 
    } 

    // Print the date 
    cout << month << " " << day << "," << year << endl; 
    return 0; 
} 

我非常感謝任何幫助。

+4

,而不是在預先確定的指標越來越子。尋找'/'索引並從那裏刪除。 – 2014-09-30 07:57:20

+0

我想使用查找成員函數...像date.find(「/」,0)來尋找/字符和從位置0搜索。我仍然應該解析出月份,日期和年日期? – JimT 2014-09-30 08:06:05

+1

@JimT ['find'](http://en.cppreference.com/w/cpp/string/basic_string/find)會爲您提供在'date.substr'調用中使用的偏移量,而不是固定值。 – zakinster 2014-09-30 08:08:29

回答

2

正如Red Serpent在評論中所寫:使用std::string::find搜索/,例如,

#include <iostream> 

int main() 
{ 
    std::string date = "09/28/1983"; 

    int startIndex = 0; 
    int endIndex = date.find('/'); 
    std::string month = date.substr(startIndex, endIndex); 

    startIndex = endIndex + 1; 
    endIndex = date.find('/', endIndex + 1); 
    std::string day = date.substr(startIndex, endIndex - startIndex); 

    std::string year = date.substr(endIndex + 1, 4); 

    std::cout << month.c_str() << " " << day.c_str() << "," << year.c_str() << std::endl; 

    return 0; 
} 
0

你也可以利用流轉換的,對於效率較低,但簡單的解決辦法:

#include <iostream> 
#include <string> 
using namespace std; 

int main() { 

    string months[] = {"", "January", "February", "Mars", "April", "May", "June", "Jully", "August", "September", "October", "December"}; 

    cout << "Enter a date (mm/dd/yyyy): " << endl; 
    char c; 
    int day, month, year; 
    cin >> day >> c >> month >> c >> year; 
    // error handling is left as an exercice to the reader. 
    cout << months[month] << " " << day << ", " << year << endl; 
    return 0; 
}