Skip to content

Commit

Permalink
Apply more suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
frederic-tingaud-sonarsource committed Oct 10, 2024
1 parent 65e8b9f commit 0b24a2a
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions rules/S7118/cfamily/rule.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
----

Expand All @@ -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()`.
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 0b24a2a

Please sign in to comment.