[英]How can I search for a character in a string?
我正在編寫將短日期(mm / dd / yyyy)轉換為長日期(2014年3月12日)並打印出日期的程序。
該程序必須在以下用戶輸入下工作:10/23/2014 9/25/2014 12/8/2015 1/1/2016
我的程序正在使用第一個用戶輸入,但是我不確定如何繼續處理在字符串的第一個位置沒有“ 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;
}
我將不勝感激任何幫助。
就像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;
}
您還可以利用流轉換來獲得效率較低但更簡單的解決方案:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.