功能
从name中找出全部数值字符,之后将name(string类)转为d(double类)
代码
#include <iostream>
#include <list>
#include <deque>
#include <vector>
#include <forward_list>
#include <array>
using namespace std;int main()
{string name("zhang2021.5san4.2");string numbers("+-.0123456789");double d; // string要转换为doubleunsigned pos = 0; // 从下标0开始搜索数值字符string over; // 存储数值字符的stringwhile ((pos = name.find_first_of(numbers, pos)) != string::npos) {string s; // 存储每一次循环搜出来的数值字符s = name.substr(pos); // 将数值字符起始位置到整体末尾的字符生成子串auto pos1 = s.find_first_not_of(numbers);// 从非数值字符位置结束if(pos1 != string::npos){over.append(name.substr(pos, pos1));pos += pos1;}else{ // 可能会有以数值字符结束的字符// 因此仅以上面的非数值字符结束是不够的// 还需要以最后出现的数值字符作为结尾auto pos2 = s.find_last_of(numbers)+1;over.append(name.substr(pos, pos2));pos += pos2;}cout << over << endl; // 调试的一部分//用来观察每次循环结束的存储数值字符的string的值}d = stod(over); // 将存储数值字符的string转化为doublecout << d << endl;return 0;
}