当前位置:网站首页>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).
边栏推荐
- 海外资深玩家的投资建议(2) 2021-05-03
- [golang learning notes] simple use of flag package, command line parsing
- 使用itextpdf提取PDF文件中的任意页码
- I, AI doctoral student, online crowdfunding research topic
- Relevant interfaces of [asp.net core] option mode
- Programming in the novel [serial 16] the moon bends in the yuan universe
- ospf终极实验——学会ospf世纪模板例题
- Record the process of the first excavation and intersection
- [golang learning notes] concurrency basis
- Is Ping An Securities' low commission account opening link safe? How to handle low commission
猜你喜欢

海外资深玩家的投资建议(2) 2021-05-03

STM32 MCU uses ADC function to drive finger heartbeat detection module

【golang学习笔记】包(package)的使用

王学岗视频编码————MediaCodec编解码

Profit logic of DFI project 2021-04-26

糖尿病遗传风险检测挑战赛Baseline

Still worrying about xshell cracking, try tabby

MVVM和MVVMLight简介及项目开发(一)

zk 是如何解决脑裂问题的

Storage structure and management disk. It's a bit like installing Win98. You need to partition and format the hard disk first
随机推荐
[problem handling] merge made by the 'ort' strategy
[unity3d daily bug] unity3d solves "the type or namespace name" XXX "cannot be found (are you missing the using directive or assembly reference?)" Etc
Introduction to I2C Principle & Application of esp32
vip股票账户在手机开通安全吗?
Introduction and project development of MVVM and mvvmlight (I)
How ZK solves the problem of cerebral fissure
【Matplotlib绘图】
Yuanqi Digitalization: existing mode or open source innovation Lixia action
记忆化搜索 - DP
众邦科技又一潜心力作 —— 陀螺匠 OA 系统
STM32+ESP8266+MQTT协议连接阿里云物联网平台
D1-h development board - Introduction to Nezha development
使用itextpdf提取PDF文件中的任意页码
Yolo7 mask recognition practice
Drools (1): introduction to drools
Crazy bull market, where to go in the second half? 2021-04-30
[acwing] weekly competition
Ways to improve the utilization of openeuler resources 01: Introduction
Array - 704. Binary search
synthesizable之Verilog可不可综合