C++ substring returning wrong results

2019-06-21 12:35发布

I have this string:

std::string date = "20121020";

I'm doing:

std::cout << "** Date: " << date << "\n";
std::cout << "Year: " << date.substr(0,4) << "\n";
std::cout << "Month: " << date.substr(4,6) << "\n";
std::cout << "Day: " << date.substr(6,8) << "\n";

But im getting:

** Date: 20121020
Year: 2012
Month: 1020
Day: 20

Notice that month should be 10, not 1020. Positions are correct, tried everything, that is it failing?

标签: c++ substring
3条回答
做个烂人
2楼-- · 2019-06-21 12:50
std::cout << "Month: " << date.substr(4,6) << "\n";

The second argument is wrong. You are specifying, "Give me as substring of 6 characters, starting at position 4."

You probably want:

std::cout << "Month: " << date.substr(4,2) << "\n";
查看更多
太酷不给撩
3楼-- · 2019-06-21 13:02

http://www.cplusplus.com/reference/string/string/substr/

string substr ( size_t pos = 0, size_t n = npos ) const;

pos Position of a character in the current string object to be used as starting character for the substring. If the position passed is past the end of the string, an out_of_range exception is thrown.

n Length of the substring. If this value would make the substring to span past the end of the current string content, only those characters until the end of the string are used. npos is a static member constant value with the greatest possible value for an element of type size_t, therefore, when this value is used, all the characters between pos and the end of the string are used as the initialization substring.

So your mistake in code is that you have expected that the second parameter to be the position of the last char instead of the length of the substring.

查看更多
女痞
4楼-- · 2019-06-21 13:11

Try this:

std::cout << "** Date: " << date << "\n";
std::cout << "Year: " << date.substr(0,4) << "\n";
std::cout << "Month: " << date.substr(4,2) << "\n";
std::cout << "Day: " << date.substr(6,2) << "\n";

I believe substr takes start and length as arguments.

查看更多
登录 后发表回答