Modern C++ Learning(6)-Strings (Basics)
Strings (Basics)
std::string Manipulation

Literals
‘a’ // char Literal
“C string Literal”
auto a = "seven of"; // type of a is char const[] |
“std::string Literal”s C++14
|
Joining
String literals that are only separated by whitespace are joined:
"first" "second"` ⇒ `"first second" |
std::string s = |
Raw String Literals
Advantage: special characters can be used without escaping
R"(raw "C"-string c:\users\joe)" |
char const[] |
C++11 |
|---|---|---|
R"(raw "std"-string c:\users\moe)"s |
std::string |
C++14 |
Syntax: R"DELIMITER(characters...)DELIMITER"
where DELIMITER can be a sequence of 0 to 16 characters except spaces, (, ) and \
String-Like Function Parameters
Use std::string_view for read-only parameters! C++17
- lightweight (= cheap to copy, can be passed by value)
- non-owning (= not responsible for allocating or deleting memory)
- read-only view (= does not allow modification of target string)
- of a string(-like) object (std::string/“literal”/…)
- primary use case: read-only funtion parameters
|
- avoids expensive temporary strings when string literals are passed to functions
- can speed up accesses by avoiding a level of indirection

| If You… | Use Parameter Type |
|---|---|
| always need a copy of the input string inside the function | std::string “pass by value” |
| want read-only access, don’t (always) need a copy, are using C++17 / 20 | #include |
| want read-only access, don’t (always) need a copy, are stuck with C++98 / 11 / 14 | std::string const& “pass by const reference” |
| want the function to modify the input string in-place (you should try to avoid such “output parameters”) | std::string & “pass by (non-const reference)” |
std::getline
- read entire lines / chunks of text at once
- target string can be re-used (saving memory)
std::string s; |
References
https://wzablog.top/blogs/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/Modern-Cpp-Learning-6-Strings-Basics/
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 王赵安的博客!
评论
