From 0b24a2ab72dd0be2552d97342bd6c49944a7d0fe Mon Sep 17 00:00:00 2001 From: Fred Tingaud Date: Thu, 10 Oct 2024 19:04:33 +0200 Subject: [PATCH] Apply more suggestions --- rules/S7118/cfamily/rule.adoc | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/rules/S7118/cfamily/rule.adoc b/rules/S7118/cfamily/rule.adoc index f452d91c087..19a5ce6494a 100644 --- a/rules/S7118/cfamily/rule.adoc +++ b/rules/S7118/cfamily/rule.adoc @@ -80,7 +80,7 @@ Testing the equality between two full strings can be directly performed using th ---- void comparisons(std::string const& s1, std::string const& s2) { bool equal = strcmp(s1.c_str(), s2.c_str()) == 0; // Noncompliant - int comparePart = strncmp(s1.c_str() + 2, s2.c_str() + 2, 10); // Noncompliant + int comparePart = strncmp(s1.c_str() + 2, s2.c_str() + 3, 10); // Noncompliant } ---- @@ -90,10 +90,17 @@ void comparisons(std::string const& s1, std::string const& s2) { ---- void comparisons(std::string const& s1, std::string const& s2) { bool equal = s1 == s2; // Compliant - int comparePart = s1.compare(2, 10, s2, 2, 10); // Compliant + int comparePart = s1.compare(2, 10, s2, 3, 10); // Compliant } ---- +With C++17 and higher, substring comparison can also be done through `std::string_view`. + +[source,cpp] +---- +auto comparePart = std::string_view(s1).substr(2, 10) <=> std::string_view(s2).substr(3, 10); +---- + === Searching a substring Either searching a substring or a single character inside a string can be done with `std::string::find()`. @@ -181,7 +188,20 @@ std::string beginning{string.c_str()}; Direct replacement of one C function with the corresponding string method may not lead to the best code overall. When replacing a C function call, you should consider what overall functionality this call is part of and whether your {cpp} version allows to implement that functionality more easily and effectively. -For example using ranges (`std::ranges::views::split`, `std::ranges::views::chunk`), using algorithms, using `std::stringstream` or `std::spanstream`, using `std::string_view`. +For example using ranges (`std::ranges::views::split`, `std::ranges::views::chunk`), using algorithms, using `std::istringstream` or `std::ispanstream`, using `std::string_view`. + +An example of a function splitting words in a moddern way could be as follow. + +[source,cpp] +---- +void treatWord(std::string_view word); + +void treatAllWords(std::string_view text) { + constexpr std::string_view delim{" "}; + for (const auto word : std::views::split(text, delim)) + treatWord(std::string_view{word}); +} +---- == Resources