Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
string_utils_example.C
Go to the documentation of this file.
1
101#include <iostream>
102#include <iomanip>
103#include <string>
104#include <vector>
105
106#include <tclap/CmdLine.h>
107
108#include <htlist.H>
109#include <ah-string-utils.H>
110
111using namespace std;
112using namespace Aleph;
113
114// =============================================================================
115// Helper functions
116// =============================================================================
117
118void print_section(const string& title)
119{
120 cout << "\n" << string(60, '=') << "\n";
121 cout << " " << title << "\n";
122 cout << string(60, '=') << "\n\n";
123}
124
125void print_subsection(const string& title)
126{
127 cout << "\n--- " << title << " ---\n";
128}
129
130void show_string(const string& label, const string& s)
131{
132 cout << label << ": \"" << s << "\"" << endl;
133}
134
135// =============================================================================
136// 1. Trimming
137// =============================================================================
138
140{
141 print_section("TRIMMING");
142
143 string s1 = " hello world ";
144 string s2 = "\t\n whitespace everywhere \r\n";
145
146 show_string("Original s1", s1);
147 show_string("Original s2", s2);
148
149 // ltrim - left trim
150 print_subsection("ltrim() - remove leading whitespace");
151 string left = s1;
152 ltrim(left);
153 show_string("After ltrim", left);
154
155 // rtrim - right trim
156 print_subsection("rtrim() - remove trailing whitespace");
157 string right = s1;
158 rtrim(right);
159 show_string("After rtrim", right);
160
161 // trim - both sides (returns new string)
162 print_subsection("trim() - both sides");
163 show_string("trim(s1)", trim(s1));
164 show_string("trim(s2)", trim(s2));
165}
166
167// =============================================================================
168// 2. Case Conversion
169// =============================================================================
170
172{
173 print_section("CASE CONVERSION");
174
175 string text = "Hola Mundo desde COLOMBIA";
176 show_string("Original", text);
177
178 // tolower
179 print_subsection("tolower()");
180 show_string("tolower", tolower(text));
181
182 // toupper
183 print_subsection("toupper()");
184 show_string("toupper", toupper(text));
185
186 // to_name - capitalize first letter
187 print_subsection("to_name() - capitalize first letter");
188 show_string("to_name(\"colombia\")", to_name("colombia"));
189 show_string("to_name(\"BOGOTA\")", to_name("BOGOTA"));
190
191 // to_Pascalcase
192 print_subsection("to_Pascalcase()");
193 show_string("to_Pascalcase(\"hello world\")", to_Pascalcase("hello world"));
194 show_string("to_Pascalcase(\"user_first_name\")", to_Pascalcase("user_first_name"));
195}
196
197// =============================================================================
198// 3. Splitting
199// =============================================================================
200
202{
203 print_section("SPLITTING");
204
205 string csv = "Bogota,Medellin,Cali,Barranquilla,Cartagena";
206 show_string("CSV string", csv);
207
208 // split
209 print_subsection("split()");
210 auto cities = split(csv, ',');
211 cout << "Split by ',':" << endl;
212 for (size_t i = 0; i < cities.size(); i++)
213 cout << " [" << i << "]: " << cities[i] << endl;
214
215 // split with different delimiter
216 print_subsection("Split with different delimiters");
217 string path = "/home/user/documents/file.txt";
218 auto parts = split(path, '/');
219 cout << "Path: \"" << path << "\"" << endl;
220 cout << "Split by '/':" << endl;
221 for (const auto& p : parts)
222 cout << " \"" << p << "\"" << endl;
223
224 // split_pos (split at position)
225 print_subsection("split_pos() - split at position");
226 string text = "Hello World";
227 auto [left, right] = split_pos(text, 5);
228 cout << "Text: \"" << text << "\"" << endl;
229 cout << "Split at position 5:" << endl;
230 cout << " Left: \"" << left << "\"" << endl;
231 cout << " Right: \"" << right << "\"" << endl;
232}
233
234// =============================================================================
235// 4. Joining
236// =============================================================================
237
239{
240 print_section("JOINING");
241
242 DynList<string> words = {"Cafe", "colombiano", "es", "el", "mejor"};
243 cout << "Words: ";
244 for (auto it = words.get_it(); it.has_curr(); it.next())
245 cout << "\"" << it.get_curr() << "\" ";
246 cout << endl;
247
248 // join with space
249 print_subsection("join()");
250 show_string("join(words, \" \")", join(words, " "));
251 show_string("join(words, \"-\")", join(words, "-"));
252 show_string("join(words, \", \")", join(words, ", "));
253
254 // concat - variadic concatenation
255 print_subsection("concat() - variadic");
256 string result = concat("Nombre: ", "Juan", ", Edad: ", 25, ", Ciudad: ", "Bogota");
257 show_string("concat result", result);
258}
259
260// =============================================================================
261// 5. String Validation
262// =============================================================================
263
265{
266 print_section("STRING VALIDATION");
267
268 // is_double
269 print_subsection("is_double()");
270 vector<string> test_doubles = {"3.14", "-2.5", "1e10", "abc", "12.3.4"};
271 for (const auto& s : test_doubles)
272 cout << " is_double(\"" << s << "\"): " << (is_double(s) ? "yes" : "no") << endl;
273
274 // is_long
275 print_subsection("is_long()");
276 vector<string> test_longs = {"42", "-100", "9999999", "3.14", "12abc"};
277 for (const auto& s : test_longs)
278 cout << " is_long(\"" << s << "\"): " << (is_long(s) ? "yes" : "no") << endl;
279
280 // is_size_t
281 print_subsection("is_size_t()");
282 vector<string> test_sizes = {"100", "0", "-5", "abc"};
283 for (const auto& s : test_sizes)
284 cout << " is_size_t(\"" << s << "\"): " << (is_size_t(s) ? "yes" : "no") << endl;
285
286 // contains
287 print_subsection("contains()");
288 string text = "Hello from Colombia";
289 cout << "Text: \"" << text << "\"" << endl;
290 cout << " contains(\"Colombia\"): " << (contains(text, "Colombia") ? "yes" : "no") << endl;
291 cout << " contains(\"Venezuela\"): " << (contains(text, "Venezuela") ? "yes" : "no") << endl;
292
293 // is_prefix
294 print_subsection("is_prefix()");
295 cout << " is_prefix(\"Hello world\", \"Hello\"): "
296 << (is_prefix("Hello world", "Hello") ? "yes" : "no") << endl;
297 cout << " is_prefix(\"Hello world\", \"World\"): "
298 << (is_prefix("Hello world", "World") ? "yes" : "no") << endl;
299}
300
301// =============================================================================
302// 6. Character Filtering
303// =============================================================================
304
306{
307 print_section("CHARACTER FILTERING");
308
309 string dirty = " Hello123 World!@# ";
310 show_string("Original", dirty);
311
312 // only_alpha
313 print_subsection("only_alpha() - keep only letters");
314 show_string("only_alpha", only_alpha(dirty));
315
316 // remove_spaces
317 print_subsection("remove_spaces()");
318 show_string("remove_spaces", remove_spaces(dirty));
319
320 // remove_symbols
321 print_subsection("remove_symbols()");
322 string with_symbols = "user@email.com";
323 show_string("Original", with_symbols);
324 show_string("remove_symbols('@.')", remove_symbols(with_symbols, "@."));
325
326 // fill_string
327 print_subsection("fill_string()");
328 string to_fill = "***secret***";
329 show_string("Before", to_fill);
330 fill_string(to_fill, 'X');
331 show_string("After fill_string('X')", to_fill);
332}
333
334// =============================================================================
335// 7. Text Formatting
336// =============================================================================
337
339{
340 print_section("TEXT FORMATTING");
341
342 string lorem = "Este es un texto de ejemplo que sera formateado de diferentes maneras para demostrar las capacidades de formateo de texto de Aleph-w.";
343
344 cout << "Original text:" << endl;
345 cout << " " << lorem << endl;
346
347 // justify_text
348 print_subsection("justify_text() - width=40");
349 string justified = justify_text(lorem, 40);
350 cout << "Justified:" << endl;
351 auto lines = split(justified, '\n');
352 for (const auto& line : lines)
353 cout << " |" << line << "|" << endl;
354
355 // align_text_to_left
356 print_subsection("align_text_to_left() - width=35");
358 lines = split(left_aligned, '\n');
359 cout << "Left aligned:" << endl;
360 for (const auto& line : lines)
361 cout << " |" << line << "|" << endl;
362}
363
364// =============================================================================
365// 8. Conversion Utilities
366// =============================================================================
367
369{
370 print_section("CONVERSION UTILITIES");
371
372 // to_string for vectors
373 print_subsection("to_string(vector)");
374 vector<int> nums = {1, 2, 3, 4, 5};
375 cout << "vector<int>: " << Aleph::to_string(nums) << endl;
376
377 vector<double> prices = {19.99, 29.99, 39.99};
378 cout << "vector<double>: " << Aleph::to_string(prices) << endl;
379
380 // to_string with precision
381 print_subsection("to_string(double, precision)");
382 double pi = 3.14159265358979;
383 cout << "pi (2 decimals): " << Aleph::to_string(pi, 2) << endl;
384 cout << "pi (6 decimals): " << Aleph::to_string(pi, 6) << endl;
385
386 // build_pars_list
387 print_subsection("build_pars_list() - parameter list");
388 string params = build_pars_list("name", 42, 3.14, "test");
389 show_string("Parameters", params);
390}
391
392// =============================================================================
393// 9. Practical Example
394// =============================================================================
395
397{
398 print_section("PRACTICAL: CSV Parser");
399
400 string csv_data = R"(
401 Nombre, Ciudad, Edad, Salario
402 Juan Perez, Bogota, 35, 5000000
403 Maria Garcia, Medellin, 28, 4500000
404 Carlos Lopez, Cali, 42, 6000000
405 )";
406
407 cout << "Raw CSV data:" << endl;
408 cout << csv_data << endl;
409
410 // Parse CSV
411 print_subsection("Parsing CSV");
412 auto lines = split(trim(csv_data), '\n');
413
414 bool is_header = true;
416
417 for (const auto& raw_line : lines)
418 {
419 string line = trim(raw_line);
420 if (line.empty()) continue;
421
422 auto fields = split(line, ',');
423
424 if (is_header)
425 {
426 cout << "Headers:" << endl;
427 for (const auto& f : fields)
428 {
429 string h = trim(f);
430 headers.push_back(h);
431 cout << " - " << h << endl;
432 }
433 is_header = false;
434 cout << "\nRecords:" << endl;
435 }
436 else
437 {
438 cout << " Record:" << endl;
439 for (size_t i = 0; i < fields.size() and i < headers.size(); i++)
440 {
441 string value = trim(fields[i]);
442 cout << " " << headers[i] << ": " << value << endl;
443 }
444 }
445 }
446
447 // Validate salaries
448 print_subsection("Validate numeric fields");
449 string salary = "5000000";
450 cout << "Salary \"" << salary << "\" is valid number? "
451 << (is_size_t(salary) ? "yes" : "no") << endl;
452
453 string invalid = "abc123";
454 cout << "Salary \"" << invalid << "\" is valid number? "
455 << (is_size_t(invalid) ? "yes" : "no") << endl;
456}
457
458// =============================================================================
459// Main
460// =============================================================================
461
462int main(int argc, char* argv[])
463{
464 try
465 {
466 TCLAP::CmdLine cmd(
467 "String utilities example for Aleph-w.\n"
468 "Demonstrates trim, split, join, case conversion, and more.",
469 ' ', "1.0"
470 );
471
472 TCLAP::ValueArg<string> sectionArg(
473 "s", "section",
474 "Run only specific section: trim, case, split, join, validate, "
475 "filter, format, convert, practical, or 'all'",
476 false, "all", "section", cmd
477 );
478
479 cmd.parse(argc, argv);
480
481 string section = sectionArg.getValue();
482
483 cout << "\n";
484 cout << "============================================================\n";
485 cout << " ALEPH-W STRING UTILITIES EXAMPLE\n";
486 cout << "============================================================\n";
487
488 if (section == "all" or section == "trim")
490
491 if (section == "all" or section == "case")
493
494 if (section == "all" or section == "split")
496
497 if (section == "all" or section == "join")
498 demo_joining();
499
500 if (section == "all" or section == "validate")
502
503 if (section == "all" or section == "filter")
505
506 if (section == "all" or section == "format")
508
509 if (section == "all" or section == "convert")
511
512 if (section == "all" or section == "practical")
514
515 cout << "\n" << string(60, '=') << "\n";
516 cout << "String utilities demo completed!\n";
517 cout << string(60, '=') << "\n\n";
518
519 return 0;
520 }
521 catch (TCLAP::ArgException& e)
522 {
523 cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
524 return 1;
525 }
526 catch (exception& e)
527 {
528 cerr << "Error: " << e.what() << endl;
529 return 1;
530 }
531}
532
String manipulation utilities.
int main()
long double h
Definition btreepic.C:154
Dynamic singly linked list with functional programming support.
Definition htlist.H:1423
size_t size() const noexcept
Count the number of elements of the list.
Definition htlist.H:1319
auto get_it() const
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:190
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
Definition ah-arena.H:89
std::string tolower(const char *str)
Convert a C std::string to lower-case.
bool is_prefix(const std::string &str, const std::string &prefix)
Check whether prefix is a prefix of str.
std::string remove_symbols(const std::string &str, const std::string &symbols)
Remove any character appearing in symbols.
std::pair< std::string, std::string > split_pos(const std::string &str, const size_t pos)
Split a std::string at a fixed position.
void ltrim(std::string &s)
Remove leading whitespace from a std::string in-place.
std::string align_text_to_left(const std::string &text, const size_t page_width, const size_t left_margin=0)
Align text to the left by wrapping lines at page_width.
bool contains(const std::string_view &str, const std::string_view &substr)
Check if substr appears inside str.
std::string to_Pascalcase(const std::string &str)
Convert an identifier-like std::string to PascalCase.
bool is_long(const std::string &str)
Check whether a std::string fully parses as a long.
std::string to_name(const std::string &str)
Uppercase the first character of str and return the resulting copy.
bool is_size_t(const std::string &str)
Check whether a std::string fully parses as a non-negative size_t.
std::string trim(const std::string &s)
Return a trimmed copy of a std::string (leading + trailing whitespace removed).
void build_pars_list(std::string &unused)
Base case for build_pars_list(std::string&, ...).
std::string remove_spaces(const std::string &str)
Remove all whitespace characters from a std::string.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
std::string justify_text(const std::string &text, const size_t width, const size_t left_margin=0)
Justify a text to a target width.
bool is_double(const std::string &str)
Check whether a std::string fully parses as a finite double.
std::string concat(const Args &... args)
Concatenate multiple streamable arguments into a single std::string.
std::string toupper(const char *str)
Convert a C std::string to upper-case.
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
void rtrim(std::string &s)
Remove trailing whitespace from a std::string in-place.
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
void fill_string(std::string &str, char sym)
Fill all the content of std::string with a defined char.
DynList< T > maps(const C &c, Op op)
Classic map operation.
std::string only_alpha(const std::string &str)
Extract alphanumeric ASCII characters and normalize letters to lower-case.
STL namespace.
void demo_splitting()
void print_subsection(const string &title)
void demo_validation()
void demo_trimming()
void demo_conversion()
void print_section(const string &title)
void demo_case_conversion()
void demo_practical()
void show_string(const string &label, const string &s)
void demo_formatting()
void demo_joining()
void demo_filtering()