C++ 内置函数 判断字母、数字及大小写转换

一、c++的几个内置函数

1.1 判断

islower(char c) :是否为小写字母
isupper(char c): 是否为大写字母
isdigit(char c) :是否为数字
isalpha(char c) :是否为字母
isalnum(char c): 是否为字母或者数字

1.2 转换

toupper(char c): 字母小转大
tolower(char c) :字母大转小

二、std 模板库的转换

2.1 string转换为其他类型

string转换为float: float stof(const string& str, size_t* idx = 0);
string转换为double: double stod(const string& str, size_t* idx = 0);
string转换为int: int stoi (const string& str, size_t* idx = 0, int base = 10);
string转换为long: long stol (const string& str, size_t* idx = 0, int base = 10);
string转换为long double: long double stold (const string& str, size_t* idx = 0);
string转换为long long: long long stoll (const string& str, size_t* idx = 0, int base = 10);
string转换为unsigned long: unsigned long stoul (const string& str, size_t* idx = 0, int base = 10);
string转换为unsigned long long: unsigned long long stoull (const string& str, size_t* idx = 0, int base = 10);

2.3 其他类型转换为string

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

三、使用sstream方式

/// 数字转换字符串
template <typename T>
std::string num_to_string(cont T& t) {
  std::ostringstream oss;
  oss << t;
  return oss.str();
}


/// 字符串转换数字
template <typename T> 
T string_to_num(const std::string& str) {
  std::istringstream iss(str);
  T num;
  iss > num;
  return num; 
}

官网

posted @ 2020-09-26 23:11  小海哥哥de  阅读(3211)  评论(0编辑  收藏  举报