ArkScript
A small, lisp-inspired, functional scripting language
Utils.cpp
Go to the documentation of this file.
1#include <Ark/Utils/Utils.hpp>
2
3#include <ranges>
4
5namespace Ark::Utils
6{
7 std::size_t levenshteinDistance(const std::string& str1, const std::string& str2)
8 {
9 const std::size_t str1_len = str1.size();
10 const std::size_t str2_len = str2.size();
11 std::vector edit_distances(str1_len + 1, std::vector<std::size_t>(str2_len + 1, 0));
12
13 for (std::size_t i = 0; i < str1_len + 1; i++)
14 edit_distances[i][0] = i;
15
16 for (std::size_t j = 0; j < str2_len + 1; j++)
17 edit_distances[0][j] = j;
18
19 for (std::size_t i = 1; i < str1_len + 1; i++)
20 {
21 for (std::size_t j = 1; j < str2_len + 1; j++)
22 {
23 const std::size_t indicator = str1[i - 1] == str2[j - 1] ? 0 : 1;
24 edit_distances[i][j] = std::min({
25 edit_distances[i - 1][j] + 1, // deletion
26 edit_distances[i][j - 1] + 1, // insertion
27 edit_distances[i - 1][j - 1] + indicator // substitution
28 });
29 }
30 }
31
32 return edit_distances[str1_len][str2_len];
33 }
34
35 long countOpenEnclosures(const std::string& line, const char open, const char close)
36 {
37 return std::ranges::count(line, open) - std::ranges::count(line, close);
38 }
39
40 void trimWhitespace(std::string& line)
41 {
42 const std::size_t string_begin = line.find_first_not_of(" \t");
43 if (std::string::npos != string_begin)
44 {
45 const std::size_t string_end = line.find_last_not_of(" \t");
46 line = line.substr(string_begin, string_end - string_begin + 1);
47 }
48 }
49}
Lots of utilities about string, filesystem and more.
ARK_API long countOpenEnclosures(const std::string &line, char open, char close)
Count the open enclosure and its counterpart: (), {}, [].
Definition Utils.cpp:35
ARK_API void trimWhitespace(std::string &line)
Remove whitespaces at the start and end of a string.
Definition Utils.cpp:40
ARK_API std::size_t levenshteinDistance(const std::string &str1, const std::string &str2)
Calculate the Levenshtein distance between two strings.
Definition Utils.cpp:7