c++11常用代码

1、字符串大小写转换

#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
void transformLiteral()
{
    string strA("testAbc@126.com");
    string strB("TestABC@163.com");
    
    transform(strA.begin(), strA.end(), strA.begin(), ::toupper);
    transform(strB.begin(), strB.end(), strB.begin(), ::tolower);      
}
 
int main()
{
    transformLiteral();
    return 0;
}

2、去除空白字符trim的实现

#include <algorithm>
#include <cctype>
#include <locale>

// trim from start(in place)
static inline void ltrim(std::string &s) {
  s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
    return !std::isspace(ch);
  }));
}

// trim from end(in place)
static inline void rtrim(std::string &s){
  s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch){
    retrun !std::isspace(ch);
  }).base(), s.end());
}

3、c++11计时

#include <chrono>

#include <thread>


auto t1 = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
auto t2 = std::chrono::steady_clock::now();
auto time_used1 = std::chrono::duration_cast<microseconds>(t2-t1);
cout << "用时:" << time_used1.count() << "微秒" << endl;

4、c++11获取系统时间戳

#include <chrono>
using namespace std;

int main()
{
    // 获取操作系统当前时间点(精确到微秒)
    chrono::time_point<chrono::system_clock, chrono::microseconds> tpMicro
        = chrono::time_point_cast<chrono::microseconds>(chrono::system_clock::now());
    // (微秒精度的)时间点 => (微秒精度的)时间戳
    time_t totalMicroSeconds = tpMicro.time_since_epoch().count();


    // (微秒精度的)时间戳 => (微秒精度的)时间间隔
    chrono::microseconds durMicro = chrono::microseconds(totalMicroSeconds);
    // (微秒精度的)时间间隔 => (微秒精度的)时间点
    tpMicro = chrono::time_point<chrono::system_clock, chrono::microseconds>(durMicro);
    // (各种精度的)时间点 => (秒精度的)时间戳
    time_t timestamp_s = std::chrono::system_clock::to_time_t(tpMicro);

    // 获取微秒时间
    int micro = (totalMicroSeconds % 1000000);


    // 将时间戳转换为时间格式
    tm time;
    gmtime_s(&time, &timestamp_s);

    char szTime[64];
    sprintf_s(szTime, "%04d-%02d-%02d %02d:%02d:%02d.%06d",
        time.tm_year + 1900, time.tm_mon + 1, time.tm_mday, (time.tm_hour + 8) % 24, time.tm_min, time.tm_sec, micro);
}

5、c++11实现字符串分割

#include <iostream>
#include <vector>
#include <iterator>
#include <regex>
/* 
   用delim指定的正则表达式将字符串in分割,返回分割后的字符串数组
   delim 分割字符串的正则表达式 
 */
std::vector<std::string> s_split(const std::string& in, const std::string& delim) {
    std::regex re{ delim };
    // 调用 std::vector::vector (InputIterator first, InputIterator last,const allocator_type& alloc = allocator_type())
    // 构造函数,完成字符串分割
    return std::vector<std::string> {
        std::sregex_token_iterator(in.begin(), in.end(), re, -1),
        std::sregex_token_iterator()
    };
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值