[英]String into integer in C++
我有這樣的字符串值: 2014-04-14
我想像這樣將其轉換為Integer 20140414
我知道字符串可以像這樣完成
std::string myString = "45";
int value = atoi(myString.c_str()); //value = 45
但我不知道如何刪除-
簽名。
您可以結合使用std :: remove和std :: vector#erase :
myString.erase(std :: remove(myString.begin(),myString.end(),'-'),myString.end());
此代碼刪除了-
。
使用流:
std::istringstream iss("2014-04-14");
然后,如果您具有C ++ 11,則可以使用新的get_time
io操作器 :
std::tm tm;
if (iss >> get_time(&tm, "%Y-%m-%d"))
...
std::tm
結構具有提取的值,即:
tm.tm_year
tm.tm_mon
tm.tm_mday
中的每月的一天(1..31) 因此,您想要的值是:
int value = (tm.tm_year + 1900) * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday;
或者,或者使用C ++ 03,您可以自己從istringstream
解析值:
int year, month, day;
char c;
if (iss >> year >> c && c == '-' &&
iss >> month >> c && c == '-' &&
iss >> day)
{
int value = year * 10000 + month * 100 + day;
... use value ...
}
else
std::cerr << "invalid date\n";
蠻力法:
const std::string text_date = "2014-04-25";
std::string text_no_dash;
for (unsigned int i = 0; i < text_date.length; ++i)
{
if (text_date[i] != '-')
{
text_no_dash += text_date[i];
}
}
此代碼顯示了僅將所需字符從字符串復制到新字符串的算法。
你試過用這個嗎? 這是我過去所做的操作,以刪除我不需要的任何符號。
char characters[] = "*()$-";
for (unsigned int i = 0; i < strlen(characters); ++i)
{
stringName.erase (std::remove(stringName.begin(), stringName.end(), characters[i]), stringName.end());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.