文章目录
- 前言
- 字符串转整数
- stoi
- isstringstream
- atoi
- 字符转整数
- to_string
- stringstream
- sprintf
- ASCII码转换
前言
题目大致为:
给一组数据,去掉里面的2,然后再返回结果
例如:
输入:{20, 66, 521, 2024}
输出:{0, 66, 51, 4}
思路是将数字转成字符串,然后去掉2,但是脑子没转过来,忘记接口了,用最原始方法转换的
字符串转整数
stoi
string
类提供了一系列字符串转数字的接口(C++11引入):
文档:C++ Reference (cplusplus.com)
这里拿stoi
举例:
int stoi (const string& str, size_t* idx = nullptr, int base = 10);
int stoi (const wstring& str, size_t* idx = nullptr, int base = 10);
str
:要转换的字符串idx
:结束未处理到的字符索引,默认为nullptr
base
:数字进制,默认十进制
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str_dec = "1234, hello world";
string str_hex = "40c3";
string str_bin = "-110101";
string str_auto = "0x7f";
size_t sz;
int i_dec = stoi(str_dec, &sz);
int i_hex = stoi(str_hex, nullptr, 16);
int i_bin = stoi(str_bin, nullptr, 2);
int i_auto = stoi(str_auto,nullptr,0); //自动识别
cout << str_dec << ": " << i_dec << " + [" << str_dec.substr(sz) << "]" << endl;
cout << str_hex << ": " << i_hex << endl;
cout << str_bin << ": " << i_bin << endl;
cout << str_auto << ": " << i_auto << endl;
}
isstringstream
从字符串流当中读取数据
文档:istringstream - C++ Reference (cplusplus.com)
#include <iostream>
#include <sstream>
int main() {
std::string str = "123";
std::istringstream iss(str);
int num;
iss >> num;
if (iss.fail())
{
std::cerr << "failed" << std::endl;
} else
{
std::cout << "Integer: " << num << std::endl;
}
return 0;
}
atoi
C语言也提供了转换接口:
拿atoi
举例:
int atoi (const char * str);
将C风格的字符串转成整数,但是这个没有错误检查机制
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char ch[] = "1234";
string s = "5678";
int n1 = atoi(ch);
int n2 = atoi(s.c_str());
cout << n1 << endl;
cout << n2 << endl;
return 0;
}
字符转整数
to_string
文档:to_string - C++ Reference (cplusplus.com)
#include<iostream>
#include<string>
int main()
{
int a = 23456;
std::string s = std::to_string(a);
std::cout << s << std::endl;
return 0;
}
stringstream
文档:stringstream - C++ Reference (cplusplus.com)
int main()
{
int a = 1234;
stringstream ss;
//整数写进字符串流
ss << a;
//字符串流提取
string s = ss.str();
cout << s << endl;
return 0;
}
sprintf
这是C语言提供的函数
#include <iostream>
#include <cstdio>
int main()
{
int num = 123;
char buffer[50];
sprintf(buffer, "%d", num);
std::string str(buffer);
std::cout << "String: " << str << std::endl;
return 0;
}
ASCII码转换
字符'0'
的ASCII码是48
转换的时候加减48即可
int main()
{
char c = '5';
int c2i = c - 48;
cout << c2i << endl;
int n = 3;
char i2c = n + 48;
cout << i2c << endl;
return 0;
}
数字字符部分ASCII码表: