CKTIS / C++
std::string::empty — string emptiness versus separator position
`std::string::empty` tests whether a string has zero length. It does not tell you whether the first argument position has already been processed when joining strings.
Version: ISO C++23; implementation support may vary
Syntax
constexpr bool empty() const noexcept;
// Call on a std::string object s declared using <string>:
s.empty()std::string::empty is a parameterless member function of std::string, the alias for std::basic_string<char> provided by <string>. Calling s.empty() returns a bool: true if s.size() == 0 and false otherwise. A single space or a \0 stored as a string element counts toward the length. The function does not check capacity.
The test takes constant time, does not modify the string, and can be called on a const object. The function has been noexcept since C++11 and constexpr since C++20, so in C++23 it can be used in constant evaluation when the whole expression meets the requirements. In s.empty() ? "" : "|", the conditional operator ?: uses the call's result to choose one of two expressions. empty() itself just returns a bool.
To preserve every position when joining arguments, insert a separator before every argument except the first, even if earlier arguments were empty. After appending an empty first argument, the result still has zero length, so testing empty() incorrectly skips the separator before the second argument. With a zero-based index, i != 0 tests position rather than the contents of the result.
Examples
#include <array>
#include <cstddef>
#include <iostream>
#include <string>
int main() {
const std::array<std::string, 3> fields{"", "beta", "gamma"};
std::string by_content;
std::string by_position;
for (std::size_t i = 0; i < fields.size(); ++i) {
by_content += (by_content.empty() ? "" : "|");
by_content += fields[i];
if (i != 0) {
by_position += '|';
}
by_position += fields[i];
}
std::cout << "content: " << by_content << '\n'
<< "position: " << by_position << '\n';
}Result
content: beta|gamma position: |beta|gamma
The first argument is empty. The first line omits the separator before `beta`; the second keeps it to mark the empty first position.
Related lessons
- C++ · Lesson 4 · Advanced · Version: 3