首页 > 编程语言 > 详细

C++17尝鲜:string_view

时间:2018-06-27 13:35:04      阅读:247      评论:0      收藏:0      [点我收藏+]

string_view

string_view 是C++17所提供的用于处理只读字符串的轻量对象。

  • 通过调用 string_view 构造器可将字符串转换为 string_view 对象。
  • string_view通常用于函数参数类型,可用来取代 const char* 和 const string&。
  • string_view的成员函数即对外接口与 string 相类似,但只包含读取字符串内容的部分。
  • string_view字面量的后缀是 sv。(string字面量的后缀是 s)

实例

#include <string>
#include <iostream>

using namespace std;

// void process(const char* sv)
// void process(const string& sv)
void process(string_view sv)
{
    cout << sv << endl;
    for (char ch : sv)
        cout << ch;
    cout << sv[2] << endl;
}

int main()
{
    string_view sv = "hello"sv;
    cout << sv << endl;
    string_view sv2 = "hello";
    cout << sv2 << endl;
    string_view sv3 = "hello"s;
    cout << sv3 << endl;
    string_view sv4("hello", 4);
    cout << sv4 << endl;
    process("hello");
    process("hello"s);
}

/*
hello
hello
hello
hell
hello
hellol
hello
hellol
*/

C++17尝鲜:string_view

原文:https://www.cnblogs.com/zwvista/p/9233396.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!