我有一个字符串“ YYYY-MM-DD”,并且想要将该字符串转换为整数并将它们分别存储为年,月,日。我使用substr并获得了年份,但我无法获得MM和DD。

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

int dayOfYear(string date)
{
    for (int i = 0; i < date.size(); i++)
    {
        if (date[i] == '-')
            date.erase(date.begin()+i);
    }
        //getting substring for year
    string str1 = date.substr(0, 4);

    string str2 = date.substr(5, 6);//getting wrong output

        //converting string to int
    int year = stoi(str1);
    int month = stoi(str2);

    return month;//getting output as 109


}

int main()
{
    string date = "2019-01-09";
    int p = dayOfYear(date);
    cout << p;
    return 0;
}

最佳答案

string::substr的第二个参数应该是count -要包含在返回的字符串中的字符数。

删除-后,date"20190109"。您需要从位置4开始并从日期获取2个字符。采用

string str2 = date.substr(4, 2);

关于c++ - 如何从字符串的中间来子字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57447190/

10-11 22:57
查看更多