簡體   English   中英

在C ++中將字符串轉換為整數

[英]String into integer in C++

我有這樣的字符串值: 2014-04-14

我想像這樣將其轉換為Integer 20140414

我知道字符串可以像這樣完成

std::string myString = "45";
int value = atoi(myString.c_str()); //value = 45

但我不知道如何刪除-簽名。

您可以結合使用std :: removestd :: 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結構具有提取的值,即:

  • 1900以來的年份存儲在tm.tm_year
  • 自一月以來的月份 (所以0..11)存儲在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM