ALib C++ Library
Library Version: 2402 R1
Documentation generated by doxygen
Loading...
Searching...
No Matches
Strings Struct Reference

Description:


This built-in CompilerPlugin of ALib Expressions compiles identifiers, functions and operators with character string type operands or return types.

By default, this plug-in is automatically created and inserted into each instance of class Compiler with the invocation of SetupDefaults .

Constants:

Type Name Min. Abbreviation Description
String NewLine nl System dependent new line character combination ( "\n" or "\r\n").
String Tabulator tab String with single tabulator character ("\t").


Functions:

Note: All identifier and function names are defined case insensitive.

Return Type Name Min. Abbreviation Signature Description
String String str ... Creates and returns a string representation of the arguments, concatenated from left to right.
String ToUpper tu String Converts all appropriate characters of a string to upper case letters. This function is aliased by unary operator '+'.
String ToLower tl String Converts all appropriate characters of a string to lower case letters. This function is aliased by unary operator '-'.
Boolean Compare comp String, String Returns 0 if strings are equal, a negative value if the first string is "smaller" than the second and a positive otherwise.
Boolean Compare comp String, String, Boolean Same as Compare(String,String) if third parameter is false. If it is true letter case is ignored.
Boolean StartsWith sw String, String Tests if the first given string starts with the second. Comparison is case sensitive.
Boolean StartsWith sw String, String, Boolean Tests if the first given string starts with the second. The third parameter is true, letter case is ignored.
Boolean EndsWith ew String, String Tests if the first given string ends with the second. Comparison is case sensitive.
Boolean EndsWith ew String, String, Boolean Tests if the first given string ends with the second. The third parameter is true, letter case is ignored.
String Substring subs String, Integer Returns the sub-string, starting at given position (2nd argument) to the end of the string..
String Substring subs String, Integer, Integer Returns the sub-string, starting at given position (2nd argument) with the given length (3rd argument).
Integer IndexOf indo String, String Searches the first occurrence of the second string in the first. Returns the position if found, otherwise -1.
Integer Count count String, String Counts the number of occurrences of the second string in the first.
String Replace repl String, String, String Returns a copy of the 1st argument, with occurrences of 2nd argument replaced by 3rd argument.
String Repeat repeat String, Integer Returns 1st argument concatenated N times (2nd argument).
String Token tok String, String, Integer Parses tokens separated by character (2nd argument) in string (1st argument) an returns the n-th (3rd argument).
String Trim trim String Trims the string at both sides by removing the following whitespace characters: ' ', '\n', '\r' and '\t'.
String Trim trim String, String Trims the string at both sides by removing the whitespace characters listed in the second string.
String TrimStart trims String Trims the string at the start by removing the following whitespace characters: ' ', '\n', '\r' and '\t'.
String TrimStart trims String, String Trims the string at the start by removing the whitespace characters listed in the second string.
String TrimEnd trime String Trims the string at the end by removing the following whitespace characters: ' ', '\n', '\r' and '\t'.
String TrimEnd trime String, String Trims the string at the end by removing the whitespace characters listed in the second string.
Integer Integer int String Parses an integral value from the string. Allows decimal, hexadecimal, octal and binary formats. Literal prefixes default to '0x', '0o' and '0b', which can be changed by configuring object DefaultNumberFormat of field Scope::Formatter .
Float Float float String Parses a floating point value from the string. Allows scientific format and change of decimal point character by configuring object DefaultNumberFormat of field Scope::Formatter .
String Hexadecimal hex Integer Converts an integral value to a hexadecimal string representation. Format options are available with object DefaultNumberFormat of field Scope::Formatter . The literal prefix (e.g. "0x") is not written.
String Hexadecimal hex Integer, Integer Converts an integral value to a hexadecimal string representation of the given output width (2nd argument). Format options are available with object DefaultNumberFormat of field Scope::Formatter . The literal prefix (e.g. "0x") is not written.
String Octal oct Integer Converts an integral value to a binary string representation. Format options are available with object DefaultNumberFormat of field Scope::Formatter . The literal prefix (e.g. "0x") is not written.
String Octal oct Integer, Integer Converts an integral value to a binary string representation of the given output width (2nd argument). Format options are available with object DefaultNumberFormat of field Scope::Formatter . The literal prefix (e.g. "0x") is not written.
String Binary bin Integer Converts an integral value to an octal string representation. Format options are available with object DefaultNumberFormat of field Scope::Formatter . The literal prefix (e.g. "0x") is not written.
String Binary bin Integer, Integer Converts an integral value to an octal string representation of the given output width (2nd argument). Format options are available with object DefaultNumberFormat of field Scope::Formatter . The literal prefix (e.g. "0x") is not written.
String Format format String, ... Formats the given variadic parameters according to the given format string. See notes below, for further information.
Boolean WildCardMatch wcm String, String Matches a string against a wildcard pattern. See notes below, for further information.
Boolean RegExMatch rem String, String Matches a string against a regex pattern. See notes below, for further information.


Unary Operators:

Return Type Operator Argument Type Description
String + String Alias to function ToUpper.
String - String Alias to function ToLower.
Boolean ! String Tests a string for emptiness. See notes below.


Binary Operators:

Return Type Lhs Type Operator Rhs Type Description
String String + Integer Concatenates an integral value to a string. The number conversion is performed using object DefaultNumberFormat of field Scope::Formatter .
String String + Float Concatenates a floating point value to a string. The number conversion is performed using object DefaultNumberFormat of field Scope::Formatter .
String String + <any> Converts a boxed value of arbitrary type to a string and appends the result to another string. The conversion of the boxed value is performed by invoking box-function FAppend .
String Integer + String Converts an integral value to a string and concatenates another string. The number conversion is performed using object DefaultNumberFormat of field Scope::Formatter .
String Float + String Converts a floating point value to a string and concatenates another string. The number conversion is performed using object DefaultNumberFormat of field Scope::Formatter .
String <any> + String Converts a boxed value of arbitrary type to a string and appends another string. The conversion of the boxed value is performed by invoking box-function FAppend .
String String + String Concatenates two strings.
Boolean String < String Compares two strings using method String::CompareTo .
Boolean String <= String Compares two strings using method String::CompareTo .
Boolean String > String Compares two strings using method String::CompareTo .
Boolean String >= String Compares two strings using method String::CompareTo .
Boolean String == String Compares two strings using method String::Equals .
Boolean String != String Compares two strings using method String::Equals .
Boolean String * String Alias to expression function WildCardMatch. See notes below, for further information.
Boolean String % String Alias to expression function RegexMatch. See notes below, for further information.
Boolean String [] Integer Returns the sub-string of length 1 at index rhs in string lhs.

Notes And Hints

Compile-Time Invokable:
All callback functions are defined compile-time invokable. This means that redundancies in string expressions emerging from operations on constant strings are optimized (pruned) by the compiler.
Underlying String Types:
While all string manipulation is based on ALib classes String , AString and Substring , due to the "harmonizing" way that string classes become boxed, none of these types appears as an expression result type. This means that custom expression functions can unbox strings that have been created by callback functions of this plug-in to their own custom string type (e.g. std::string, QString, or whatever), and, the other way round, results of custom callback functions that returned custom strings objects, can seamlessly be used by functions and operators defined here.

Details of this are explained in chapters 3. Non-Bijective Type Relationships and 10. Boxing Character Strings of the Programmer's Manual of module ALib Boxing .

Determine A String's Length
The length of the string can be determined with function Length, which is defined with compiler plugin Arithmetics (because it works on all arrays).
Test For Empty Strings:
Unary operator BoolNot ('!') may be used to check if a string is not empty. The operator returns true if the string is empty and false otherwise.
Consequently, to test for non-empty strings, '!!' may be written. The outer not-operator is then a not-operator on the boolean result of the inner.
Alternatively, binary operators (see below) against an emtpy string can be used:
    myIndentifier == ""
    myIndentifier != ""
As a result, this expressions is a tautology:
    !myIdentifier == (myIndentifier == "")
Finally with strings, the built-in implementation of the elvis operator is quite useful to avoid empty strings. The expression:
    myIdentifier ?: "Default"
returns "Default" if myIdentifier evaluates to an empty string.
Case conversion:
Unary operators Positive '+' and Negative '-' are alias to functions ToUpper and ToLower. Hence, the expressions
     ToUpper( "Hello " ) + ToLower( "World" )
     +"Hello " + -"World"
are equivalent.
Concatenation:
Binary operator '+' is compiled by this plug-in if one of the arguments (or both) is of string type. If one argument is not of string type, it becomes converted. For the conversion, the following rules apply:
  • Types Integer and Float are converted to string types using object DefaultNumberFormat of field Scope::Formatter . With this, detailed options for the number output format is available. Even more options are available when using expression function Format instead of the '+' operator.
  • Any other type is converted to a string representation by using box-function FAppend . For information on how to implement this for custom types, consult the documentation of module ALib Boxing . The following provides a quick sample snippet, taken from the unit tests:

    1. The custom type:
      struct MyType
      {
      String Name= A_CHAR("Joe");
      integer Age= 42;
      };
    2. Definition of functor T_Append type MyType. Because the type will be boxed as a pointer, we also define the functor for the pointer type:
      ALIB_STRINGS_APPENDABLE_TYPE_INLINE( ut_aworx::MyType , target << src.Name << '/' << src.Age; )
      ALIB_STRINGS_APPENDABLE_TYPE_INLINE( ut_aworx::MyType*, target << src->Name << '/' << src->Age; )
    3. In the bootstrap section of an application, an implementation of the templated interface function has be registered with ALib Boxing :

    With this short setup code, objects of type MyType, which might be returned by custom identifiers, can be added to strings in expressions!

  • With type Boolean , the resourced string values generally used with box-function FAppend defined for C++ type bool are used. These string resources default to "true" and "false". While resources can be customized, such customization has process-wide effect.
    To express other values, conditional operator (Q ? T : F) can be used by the end-user:
    "Is true: " + {boolean expression}                     // Uses the global resourced strings
    "Is true: " + ( {boolean expression} ? "Yes" : "No" )  // Custom conversion per expression.
    
    Comparison:
    Operators '==', '!=', '<', '<=', '>' and '>=' perform comparisons between two string operands. Internally, to perform the comparison, methods String::Equals and String::CompareTo are used.
    Case insensitive comparison can be performed by converting the operand(s) to upper case using expression function ToUpper or its "alias operator", unary '+'. A more effective way is to use overloaded function Compare that accepts an optional third operator of type Boolean, which if true is given performs a case insensitive search without performing string conversions.

Formatting:
Function Format(String, ...) offers full featured string formatting in expressions. Being based on classes of underlying module ALib BaseCamp , there is a choice between python style or Java/printf style format strings. It is even possible to allow both formats, of-course not within the same string, but within different evaluations of the same expression!
Please consult the documentation of classes
Wildcard Match:
Wildcard match is implemented with expression function WildcardMatch, respectively its "alias operator" '*'. The first (left-hand side) argument is the string that is searched, the second (right-hand side) argument is the pattern string to be matched.
Wildcards characters are ('*') and ('?'). For example, expressions
     WildcardMatch("This is ALib Expressions", "*A?ib*")
     "This is ALib Expressions" * "*A?ib*"
are equivalent and return boolean true.
For case insensitive search, the both strings are to be converted to upper case, as in expression:
     +filename  *  "*.JPG"
Note
A more performant alternative for the latest sample expression is:
   EndsWith( filename, ".jpg", true )
Regular Expression Match:
Regular expression match is implemented with expression function RegexMatch, respectively its "alias operator" '%'. The first (left-hand side) argument is the string that is searched, the second (right-hand side) argument is the pattern string to be matched.
The regular expression syntax is compatible with Perl Regular Expressions . The feature is implemented with using boost::regex library .
Attention
The regular expression features of ALib and therefore of this compiler plug-in, are only available with the definition of compiler symbol ALIB_FEAT_BOOST_REGEX and if either ALIB_CHARACTERS_WIDE is false or ALIB_CHARACTERS_NATIVE_WCHAR equals true.

Reference Documentation

Definition at line 289 of file strings.hpp.

#include <strings.hpp>

Inheritance diagram for Strings:
[legend]
Collaboration diagram for Strings:
[legend]

Public Method Index:

ALIB_API Strings (Compiler &compiler)
 
virtual ~Strings () override
 
virtual ALIB_API bool TryCompilation (CIBinaryOp &ciBinaryOp) override
 
virtual ALIB_API bool TryCompilation (CIFunction &ciFunction) override
 
- Public Method Index: inherited from Calculus
 Calculus (const NString &name, Compiler &compiler)
 
virtual ~Calculus () override
 
ALIB_API void AddBinaryOpOptimizations (BinaryOpOptimizationsTableEntry *table, size_t length)
 
template<size_t TCapacity>
void AddBinaryOpOptimizations (BinaryOpOptimizationsTableEntry(&table)[TCapacity])
 
void AddOperator (const String &op, Type lhsType, Type rhsType, CallbackDecl callback, const char *dbgCallbackName, Type resultType, CTInvokable cti)
 
void AddOperatorAlias (const String &alias, Type lhsType, Type rhsType, const String &op)
 
void AddOperatorAliases (OperatorAliasTableEntry *table, size_t length)
 
template<size_t TCapacity>
void AddOperatorAliases (OperatorAliasTableEntry(&table)[TCapacity])
 
ALIB_API void AddOperators (OperatorTableEntry *table, size_t length)
 
template<size_t TCapacity>
void AddOperators (OperatorTableEntry(&table)[TCapacity])
 
virtual ALIB_API bool TryCompilation (CIAutoCast &autoCast) override
 
virtual ALIB_API bool TryCompilation (CIUnaryOp &ciUnaryOp) override
 
- Public Method Index: inherited from CompilerPlugin
 CompilerPlugin (const NString &name, Compiler &compiler)
 
virtual ~CompilerPlugin ()
 

Additional Inherited Members

- Public Type Index: inherited from Calculus
using BinaryOpOptimizationsTableEntry = const std::tuple<String, lang::Side, Type, const Box&, const Box&>
 
using CTInvokable = bool
 
using OperatorAliasTableEntry = const std::tuple<String, Type, Type, String>
 
using OperatorTableEntry
 
- Public Static Field Index: inherited from Calculus
static constexpr CTInvokable CTI = true
 
static constexpr CTInvokable ETI = false
 
- Public Field Index: inherited from Calculus
MonoAllocator allocator
 
std::vector< AutoCastEntryAutoCasts
 
HashMap< BinOpOptKey, Box, BinOpOptKey::Hash, BinOpOptKey::EqualToBinaryOperatorOptimizations
 
std::vector< ConstantIdentifierEntryConstantIdentifiers
 
std::vector< FunctionEntryFunctions
 
HashMap< OperatorKey, String, OperatorKey::Hash, OperatorKey::EqualToOperatorAliases
 
HashMap< OperatorKey, std::tuple< CallbackDecl, Box, CTInvokable ALIB_DBG(, const char *) >, OperatorKey::Hash, OperatorKey::EqualToOperators
 
- Public Field Index: inherited from CompilerPlugin
CompilerCmplr
 
const NString Name
 

Constructor(s) / Destructor Details::

◆ Strings()

ALIB_API Strings ( Compiler & compiler)

Constructor. Creates the hash map.

Parameters
compilerThe compiler we will get attached to.

◆ ~Strings()

virtual ~Strings ( )
inlineoverridevirtual

Virtual destructor

Definition at line 300 of file strings.hpp.

Method Details:

◆ TryCompilation() [1/2]

virtual ALIB_API bool TryCompilation ( CIBinaryOp & ciBinaryOp)
overridevirtual

Overwrites the implementation of class Calculus. While this is usually not needed, this class uses this to fetch arbitrary boxed types for certain operations, because the interface mechanics of module ALib Boxing allows us to convert any custom type to a string.

Of-course, the original method is called alternatively.

Parameters
[in,out]ciBinaryOpThe compilation info struct.
Returns
true if compilation information was given, false otherwise.

Reimplemented from Calculus.

◆ TryCompilation() [2/2]

virtual ALIB_API bool TryCompilation ( CIFunction & ciFunction)
overridevirtual

Overwrites the implementation of class Calculus. While this is usually not needed, this class uses this for wildcard and regular expression matching functions. These functions implement a special behavior in respect to allocate "matcher" classes at compile-time in the case that the pattern string is constant (which usually is). Parent helper class Calculus does provide mechanics for such rather complicated special actions.

Of-course, the original method is called alternatively.

Parameters
[in,out]ciFunctionThe compilation info struct.
Returns
true if compilation information was given, false otherwise.

Reimplemented from Calculus.


The documentation for this struct was generated from the following file: