string
string的查找
string::npos
string::npos是一个静态成员常量,表示size_t的最大值(Maximum value for size_t)。该值表示“直到字符串结尾”,作为返回值它通常被用作表明没有匹配。
string::npos是这样定义的:
static const size_type npos = -1;
因为string::size_type描述的是size,故需为无符号整数型类别。因为缺省配置为size_t作为size_type,于是-1被转换为无符号整数类型,npos也就成为了该类别的最大无符号值。不过实际值还是取决于size_type的实际定义类型,即无符号整型(unsigned int)的-1与无符号长整型(unsigned long)的-1是不同的。
string::npos通常配合string::find()函数使用
string::find()函数:是一个字符或字符串查找函数,该函数有唯一的返回类型,即string::size_type,即一个无符号整形类型,可能是整数,也可能是长整数。如果查找成功,返回按照查找规则找到的第一个字符或者子串的位置;如果查找失败,返回string::npos,即-1(当然打印出的结果不是-1,而是一个很大的数值,那是因为它是无符号的)。
#include <iostream>
#include <limits>
#include <string>
std::string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
void result(const char* p)
{
std::string::size_type position = s.find(p);
if ( position != std::string::npos )
{
std::cout << "Position is : " << position << std::endl;
}
else{
std::cout << "Not found." << std::endl;
}
}
int main()
{
result("jk");
result("b3");
return 0;
}
string的类型转换
C语言写法
1.头文件
#include <stdlib.h>
2.函数声明
int atoi(const char *nptr);//将字符串转换为int
long atol(const char *nptr);//将字符串转换为long int
float atof(const char *nptr);//将字符串转换为float
double atof(const char *nptr);//将字符串转换为double
3.例子
string a = "10";
int t = atoi(a.c_str());//注意string类型使用时一定要加.c_str()转换成字符串类型
C++语言(推荐)
1.函数原型(以std::stod为例)
double stod (const string& str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
2.函数功能
将std::string字符串转化为双精度类型
3.函数参数
str : 待转换的字符串
idx : 如果idx的指针不为空,则该函数会将idx的值设置为str当前解析完成的数值字符串之后的下一个字符的位置。
4.函数返回值
如果成功则返回转换的double型数值,如果转换失败,则会抛出invalid_argument异常,如果待转换的字符所代表的数值超出数值类型范围的两倍,则会抛出out_of_range异常。
使用stod函数,stod(string对象.c_str())
即会返回float类型的值;
a = "10.5";
double t_2 = std::stod(a.c_str());
这里说明一下参数idx的意义和作用:
如果当我们的字符串中只有一个double型数值时我们可以这样进行转化:
#include <iostream>
#include <string>
int main()
{
std::string numStr = "5646545.32";
double number1 = std::stod(numStr);
getchar();
return 0;
}
但是如果字符串中有两个double型的数值该如何进行转化呢?这个时候我们就可以使用参数idx存储上一个double数值解析完成之后的在字符串中的索引,代码如下:
#include <iostream>
#include <string>
int main()
{
std::string numStr = "5646545.32 3.1415923";
size_t idx = 0;
double number1 = std::stod(numStr, &idx);
double number2 = std::stod(numStr.substr(idx));
getchar();
return 0;
}
类型转换 | value |
---|---|
string转double | std::stod |
string转float | std::stof |
string转int | std::stoi |
string转long int | std::stol |
string转long double | std::stold |
string转long long | std::stoll |
string转unsigned long | std::stoul |
string转unsigned long long | std::stoull |
数字转string | std::to_string() |