当前位置:网站首页>Absl tutorial (4): strings Library
Absl tutorial (4): strings Library
2022-07-23 22:41:00 【fdsafwagdagadg6576】
The absl/strings The library provides for manipulating and comparing strings 、 Other types ( For example, integers ) Classes and utility functions that convert to strings or evaluate strings for other purposes . Besides , The strings The library also contains information for storing data in continuous memory “ The class string ” Class .
This document provides an overview of strings Highlights of the library and general use cases . About specific classes 、 More details on functions and fields , See the source documentation in the specific header file .
Even though “ character string ” It's usually thought of as C++ Standard types in , But they are not built-in types , But through std::string Class is provided in the standard library . Basically , A string consists of a size and a char An array of characters .
absl::string_view Container
Usually , You need to access string data , But you don't need to have it , There is no need to modify it . For this reason ,Abseil Defined a absl::string_view class , It points to a continuous range of characters , Usually another std::string Double quoted string text 、 Character array or even another Part or all of string_view.A string_view, seeing the name of a thing one thinks of its function , Provides a read-only view of its associated string data .
majority C++ Code has always used ( The older )Cchar* Pointer type or C++std::string Class to save character data . If you want to use these two types of data, if you want to avoid copying data , Usually you need to provide an overloaded implementation .Astring_view It also acts as an interface that accepts two types of character data API The wrapper ; Methods can simply declare that they accept absl::string_view.
// A common use of string_view: Foo() can accept both char* and std::string via
// implicit conversion to string_view.
void Foo(absl::string_view s) { ... }string_view Objects are very lightweight , So you should always pass them by value in methods and functions ; Don't pass const absl::string_view &. ( Pass on absl::string_view instead of const absl::string_view & With the same algorithm complexity , But due to the rules of register allocation and parameter transfer , In this case, passing by value is usually faster .)
As mentioned above , because string_view It does not own the underlying data , So it should only be used for read-only data . If you need to go outside API User supplied string constants , for example :
// C++17: A read-only string in a header file.
inline constexpr absl::string_view kGreeting = "hi";
// C++11: A read-only string in a header file. Due to lifetime issues, a
// string_view is usually a poor choice for a return value (see below), but it's
// safe here because the static storage outlives it.
inline absl::string_view GetGreeting() {
static constexpr char kGreeting[] = "hi";
return kGreeting;
}string_view If you know that the life cycle of the underlying object is longer than string_view Life cycle of variable ,A It also applies to local Variable . however , Note that it is bound to a temporary value :
// BAD use of string_view: lifetime problem
absl::string_view sv = obj.ReturnAString();
// GOOD use of string_view: str outlives sv
std::string str = obj.ReturnAString();
absl::string_view sv = str; Due to life cycle problems ,string_view For the return value a It's usually a bad choice , It is almost always a bad choice for data members . If you do use one in this way , It is your responsibility to ensure string_view No more than the object it points to .
Astring_view It can represent the whole string or just a part of the string . for example , When splitting strings ,std::vector<absl::string_view> Is the natural data type of output .
Be careful : of For more information string_view, see also abseil.io/tips/1.
Be careful : More information about constant safety idioms , see also abseil.io/tips/140.
absl::StrSplit() Used to split strings
The absl::StrSplit() Function provides a simple way to split a string into substrings .StrSplit() Accept the input string to be split 、 Delimiter of the split string ( For example, comma ,) and ( Optional ) Predicate as filter , To determine whether to include split elements in the result set . StrSplit() Also adjust the returned collection to the type specified by the caller .
Example :
// Splits the given string on commas. Returns the results in a
// vector of strings. (Data is copied once.)
std::vector<std::string> v = absl::StrSplit("a,b,c", ','); // Can also use ","
// v[0] == "a", v[1] == "b", v[2] == "c"
// Splits the string as in the previous example, except that the results
// are returned as `absl::string_view` objects, avoiding copies. Note that
// because we are storing the results within `absl::string_view` objects, we
// have to ensure that the input string outlives any results.
std::vector<absl::string_view> v = absl::StrSplit("a,b,c", ',');
// v[0] == "a", v[1] == "b", v[2] == "c"StrSplit() Use transitive Delimiter Object split string .( see also Below Separator .) however , in many instances , You can simply pass string text as a delimiter ( It will be implicitly converted to absl::ByString Separator ).
Example :
// By default, empty strings are *included* in the output. See the
// `absl::SkipEmpty()` predicate below to omit them{#stringSplitting}.
std::vector<std::string> v = absl::StrSplit("a,b,,c", ',');
// v[0] == "a", v[1] == "b", v[2] == "", v[3] = "c"
// You can also split an empty string
v = absl::StrSplit("", ',');
// v[0] = ""
// The delimiter need not be a single character
std::vector<std::string> v = absl::StrSplit("aCOMMAbCOMMAc", "COMMA");
// v[0] == "a", v[1] == "b", v[2] == "c"
// You can also use the empty string as the delimiter, which will split
// a string into its constituent characters.
std::vector<std::string> v = absl::StrSplit("abcd", "");
// v[0] == "a", v[1] == "b", v[2] == "c", v[3] = "d"Adapt to the return type
StrSplit()API One of the more useful features is its ability to adjust its result set to the desired return type .StrSplit() The returned set may contain std::string、absl::string_view Or anything from absl::string_view. This model applies to all standards STL Containers , Include std::vector,std::list,std::deque,std::set, std::multiset,std::map, and std::multimap, even to the extent that std::pair, This is an impractical container .
Example :
// Stores results in a std::set<std::string>, which also performs de-duplication
// and orders the elements in ascending order.
std::set<std::string> s = absl::StrSplit("b,a,c,a,b", ',');
// s[0] == "a", s[1] == "b", s[3] == "c"
// Stores results in a map. The map implementation assumes that the input
// is provided as a series of key/value pairs. For example, the 0th element
// resulting from the split will be stored as a key to the 1st element. If
// an odd number of elements are resolved, the last element is paired with
// a default-constructed value (e.g., empty string).
std::map<std::string, std::string> m = absl::StrSplit("a,b,c", ',');
// m["a"] == "b", m["c"] == "" // last component value equals ""
// Stores first two split strings as the members in a std::pair. Any split
// strings beyond the first two are omitted because std::pair can hold only two
// elements.
std::pair<std::string, std::string> p = absl::StrSplit("a,b,c", ',');
// p.first = "a", p.second = "b" ; "c" is omittedSeparator
The StrSplit()API Provides a lot “ Separator ”, The behavior used to provide special delimiters .Delimiter The implementation contains a Find() function , This function knows how to do it in a given absl::string_view. Delimiter The conceptual model represents a particular type of separator , For example, a single character 、 Substring , Even regular expressions .
following Delimiter Abstract as StrSplit() API Part of provides :
absl::ByString()(std::stringThe default value of the parameter )absl::ByChar()(charThe default value of the parameter )absl::ByAnyChar()( Used for mixed delimiters )absl::ByLength()( Used to apply delimiters a certain number of times )absl::MaxSplits()( Used to split a specific number )
Example :
// Because a `string` literal is converted to an `absl::ByString`, the following
// two splits are equivalent.
std::vector<std::string> v = absl::StrSplit("a,b,c", ",");
std::vector<std::string> v = absl::StrSplit("a,b,c", absl::ByString(","));
// v[0] == "a", v[1] == "b", v[2] == "c"
// Because a `char` literal is converted to an `absl::ByChar`, the following two
// splits are equivalent.
std::vector<std::string> v = absl::StrSplit("a,b,c", ',');
// v[0] == "a", v[1] == "b", v[2] == "c"
std::vector<std::string> v = absl::StrSplit("a,b,c", absl::ByChar(','));
// v[0] == "a", v[1] == "b", v[2] == "c"
// Splits on any of the given characters ("," or ";")
vector<std::string> v = absl::StrSplit("a,b;c", absl::ByAnyChar(",;"));
// v[0] == "a", v[1] == "b", v[2] == "c"
// Uses the `absl::MaxSplits` delimiter to limit the number of matches a
// delimiter can have. In this case, the delimiter of a literal comma is limited
// to matching at most one time. The last element in the returned collection
// will contain all unsplit pieces, which may contain instances of the
// delimiter.
std::vector<std::string> v = absl::StrSplit("a,b,c", absl::MaxSplits(',', 1));
// v[0] == "a", v[1] == "b,c"
// Splits into equal-length substrings.
std::vector<std::string> v = absl::StrSplit("12345", absl::ByLength(2));
// v[0] == "12", v[1] == "34", v[2] == "5"Filter predicates
Predicates can StrSplit() Filter the results of the operation by determining whether the result elements are included in the result set . Filter predicates can be used as Optional The third parameter is passed to StrSplit() function .
Predicate must be a unary function ( Or functor ), They accept individual absl::string_view Parameter and returns a Boolean value , Indicates whether the parameter should be included ( true) Or exclude ( false).
边栏推荐
- Leetcode high frequency question 62. different paths: how many paths does the robot have from the upper left corner to the lower right corner? Pure probability permutation and combination problem, not
- el-select下拉框多选远程搜索反显
- 多线程问题:为什么不应该使用多线程读写同一个socket连接?
- I, AI doctoral student, online crowdfunding research topic
- D2admin framework is basically used
- How about opening an account for Haitong Securities? Is it safe
- Linked list - 203. remove linked list elements
- 海外资深玩家的投资建议(3) 2021-05-04
- What if the content of software testing is too simple?
- ES6箭头函数的使用
猜你喜欢

使用itextpdf提取PDF文件中的任意页码

Matlab小波工具箱导入信号出错(doesn‘t contain one dimensional Singal)

Life always needs a little passion
The font of Siyuan notes is thinner and lighter than that in other editors (atom, VSC, sublime)

Extract any page number in PDF file with itextpdf

The simple use of ADB command combined with monkey is super detailed

人生总需要一点激情

Excel password related

Rails with OSS best practices

Array - 59. Spiral matrix II
随机推荐
Tools in the tools package of Damon database (operate Damon database)
Leetcode high frequency question 62. different paths: how many paths does the robot have from the upper left corner to the lower right corner? Pure probability permutation and combination problem, not
QT set cache and compile output path
STM32+ESP8266+MQTT协议连接阿里云物联网平台
众邦科技又一潜心力作 —— 陀螺匠 OA 系统
Programming in the novel [serial 19] the moon bends in the yuan universe
Profit logic of DFI project 2021-04-26
02. Supplement of knowledge related to web page structure
小说里的编程 【连载之二十】元宇宙里月亮弯弯
MySQL的 DDL和DML和DQL的基本语法
I, AI doctoral student, online crowdfunding research topic
Programming in the novel [serial 20] the moon bends in the yuan universe
Array - 977. Square of ordered array
DeFi项目的盈利逻辑 2021-04-26
【AcWing】周赛
[C language] address book (static version)
使用itextpdf提取PDF文件中的任意页码
作为开发,你不得不知道的三个性能测试工具|Jmeter、Apipost、JMH使用指南
Multithreading problem: why should we not use multithreading to read and write the same socket connection?
Rosbag file recorded by LIDAR point cloud data is converted into CSV file