輸入輸出示例
輸入:
9 October 2001
14 October 2001
輸出:
Tuesday
Sunday
【原題鏈接】
字符串處理
C風格的字符串
- 字符數組,以’\0‘結尾
- 建議在輸入輸出語句中使用
C++風格的字符串
#include <string>
using namespace std;
- 初始化:string str1 = str;//world
- 連接: str1 + “hello” //即"worldhello"
- 字符:str1[0]//即’w’
- 長度:str1.length();
- 判斷相符:str1 == “world”
- 比較字典順序:str1 > “abandon”
- 從C++風格到C風格:str1.c_str();
字符串到數字的對應:map映射
#include <map>
using namespace std;
map<string,string> myMap = {//<鍵key的類型,值value的類型>{"Caixukun","ikun"},{"Wuyifan","meigeni"}};char str[100];scanf("%s",str);string name = str;printf("%s的粉絲被稱為%s\n",name.c_str(),myMap[name].c_str());
星期的計算
根據今天是星期幾,計算要求日期距離今天的距離,然后計算其星期數即可
#include <cstdio>
#include <string>
#include <map>
using namespace std;
int main() {map<string,int> month2int = {{"January",1},{"February",2},{"March",3},{"April",4},{"May",5},{"June",6},{"July",7},{"August",8},{"September",9},{"October",10},{"November",11},{"December",12}};int month_Day[13]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};string int2Weekday[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};int year, mon, day;char str[100];string month;bool isBefore;//在過去還是在未來while(scanf("%d%s%d",&day,str,&year)!=EOF){month = str;//把字符串從C風格轉換成C++風格mon = month2int[month];if (year < 2024||2024 == year && mon <3 || 2024 ==year &&mon==3&&day <10){isBefore= true;}else{isBefore= false;}//從begin走到endint beginYear, beginMon, beginDay, endYear, endMonth, endDay;if (isBefore){beginYear = year;beginMon = mon;beginDay = day;endYear = 2024;endMonth = 3;endDay = 10;} else{beginYear = 2024;beginMon = 3;beginDay = 10;endYear = year;endMonth = mon;endDay = day;}//2024年3月10日是星期日int totalDay = 0;while(true){if (beginYear==endYear&&beginMon==endMonth&&beginDay==endDay){break;}++totalDay;//next daybool isLeap = beginYear%400==0||beginYear%100!=0&&beginYear%4==0;if(isLeap){month_Day[2]=29;} else{month_Day[2]=28;}++beginDay;if (beginDay>month_Day[beginMon]){beginDay = 1;++beginMon;if (beginMon>12){beginMon=1;beginYear++;}}}if (isBefore){printf("%s\n",int2Weekday[7-totalDay%7].c_str());}else{printf("%s\n",int2Weekday[(totalDay)%7].c_str());}}return 0;
}