Contenido

# Servicio ScriptForge.String

The String service provides a collection of methods for string processing. These methods can be used to:

- Validate the contents of strings

- Format strings by trimming, justifying or wrapping their contents

- Utilizar expresiones regulares para encontrar y sustituir subcadenas

- Apply hash algorithms on strings, etc.

## Definiciones

### Saltos de renglón

The String service recognizes the following line breaks:

Nombre simbólico | Número en ASCII
--- | ---
Line feed Vertical tab Carriage return Carriage return + Line feed File separator Group separator Record separator Next line Line separator Paragraph separator | 10 12 13 13 + 10 28 29 30 133 8232 8233

### Espacios en blanco

The String service recognizes the following whitespaces:

Nombre simbólico | Número en ASCII
--- | ---
Espacio Tabulación horizontal Avance de renglón Tabulación vertical Avance de página Retorno de carro Próximo renglón Espacio indivisible Separador de renglón Separador de párrafo | 32 9 10 11 12 13 133 160 8232 8233

### Secuencias de escape

A continuación se ofrece una lista de secuencias de escape que pueden utilizarse en las cadenas.

Secuencia de escape | Nombre simbólico | Número en ASCII
--- | --- | ---
\n \r \t | Avance de renglón Retorno de carro Tabulación horizontal | 10 13 9

To have the escape sequence "\n" interpreted as an actual string, simply use "\\n" instead of "\" & Chr(10).

### Caracteres no imprimibles:

Todos aquellos caracteres que en la Base de datos de Unicode se clasifican como «Otros» o «Separador» se consideran caracteres no imprimibles.

Control characters (ASCII code <= 0x1F) are also considered as non-printable.

### Quotes inside strings:

To add quotes in strings use \' (single quote) or \" (double quote). For example:

- The string [str\'i\'ng] is interpreted as [str'i'ng]

- The string [str\"i\"ng] is interpreted as [str"i"ng]

## Invocación del servicio

Before using the ScriptForge.String service the ScriptForge library needs to be loaded using:

##### En BASIC

          GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

Loading the library will create the SF_String object that can be used to call the methods in the String service.

The following code snippets show the three ways to call methods from the String service (the Capitalize method is used as an example):

        Dim s as String : s = "abc def"
        s = SF_String.Capitalize(s) ' Abc Def

        Dim s as String : s = "abc def"
        Dim svc : svc = SF_String
        s = svc.Capitalize(s) ' Abc Def

        Dim s as String : s = "abc def"
        Dim svc : svc = CreateScriptService("String")
        s = svc.Capitalize(s) ' Abc Def

##### En Python

The code snippet below illustrates how to invoke methods from the String service in Python scripts. The IsIPv4 method is used as an example.

        from scriptforge import CreateScriptService
        svc = CreateScriptService("String")
        ip_address = '192.168.0.14'
        svc.IsIPv4(ip_address) # True

## Propiedades

The SF_String object provides the following properties for Basic scripts:

Nombre | De solo lectura | Descripción
--- | --- | ---
sfCR | Sí | Carriage return: Chr(13)
sfCRLF | Sí | Carriage return + Linefeed: Chr(13) & Chr(10)
sfLF | Sí | Linefeed: Chr(10)
sfNEWLINE | Sí | Carriage return + Linefeed, which can be 1) Chr(13) & Chr(10) or 2) Linefeed: Chr(10) depending on the operating system.
sfTAB | Sí | Tabulación horizontal: Chr(9)

You can use the properties above to identify or insert the corresponding characters inside strings. For example, the Linefeed can be replaced by SF_String.sfLF.

Lista de métodos en el servicio String
Capitalize Count EndsWith Escape ExpandTabs FilterNotPrintable FindRegex HashStr HtmlEncode IsADate IsAlpha IsAlphaNum IsAscii IsDigit IsEmail | IsFileName IsHexDigit IsIBAN IsIPv4 IsLike IsLower IsPrintable IsRegex IsSheetName IsTitle IsUpper IsUrl IsWhitespace JustifyCenter JustifyLeft | JustifyRight Quote ReplaceChar ReplaceRegex ReplaceStr Represent Reverse SplitLines SplitNotQuoted StartsWith TrimExt Unescape Unquote Wrap

The first argument of most methods is the string to be considered. It is always passed by reference and left unchanged. Methods such as Capitalize, Escape, etc return a new string after their execution.

Because Python has comprehensive built-in string support, most of the methods in the String service are available for Basic scripts only. The methods available for Basic and Python are: HashStr, IsADate, IsEmail, IsFileName, IsIBAN, IsIPv4, IsLike, IsSheetName, IsUrl, SplitNotQuoted and Wrap.

## Capitalize

Convierte en mayúscula el primer carácter de cada una de las palabras en la cadena de entrada.

### Sintaxis:

svc.Capitalize(inputstr: str): str

### Parámetros:

inputstr: la cadena que se va a escribir en mayúsculas.

### Ejemplo:

        Dim sName as String : sName = "john smith"
        Dim sCapitalizedName as String
        sCapitalizedName = SF_String.Capitalize(sName)
        MsgBox sCapitalizedName 'John Smith

## Count

Cuenta la cantidad de ocurrencias de una subcadena o una expresión regular dentro de una cadena.

### Sintaxis:

svc.Count(inputstr: str, substring: str, [isregex: bool], [casesensitive: bool]): int

### Parámetros:

inputstr: la cadena de entrada que se va a examinar.

substring: la subcadena o la expresión regular que se utilizará durante la búsqueda

isregex: Use True if the substring is a regular expression (Default = False)

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

        'Cuenta las ocurrencias de la subcadena «o» dentro de la cadena de entrada (devuelve 2)
        MsgBox SF_String.Count("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "or", CaseSensitive := False)
        'Cuenta las palabras que solo tienen letras minúsculas (devuelve 7)
        MsgBox SF_String.Count("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "\b[a-z]+\b", IsRegex := True, CaseSensitive := True)

Para conocer más sobre las expresiones regulares, consulte la documentación de Python tocante a las operaciones con expresiones regulares.

## EndsWith

Returns True if a string ends with a specified substring.

The function returns False when either the string or the substring have a length = 0 or when the substring is longer than the string.

### Sintaxis:

svc.EndsWith(inputstr: str, substring: str, [casesensitive: bool]): bool

### Parámetros:

inputstr: la cadena que se someterá a prueba.

substring: The substring to be searched at the end of inputstr.

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

        'Returns True because the method was called with the default CaseSensitive = False
        MsgBox SF_String.EndsWith("abcdefg", "EFG")
        'Devuelve False debido al parámetro CaseSensitive
        MsgBox SF_String.EndsWith("abcdefg", "EFG", CaseSensitive := True)

## Escape

Converts linebreaks and tabs contained in the input string to their equivalent escaped sequence (\\, \n, \r, \t).

### Sintaxis:

svc.Escape(inputstr: str): str

### Parámetros:

inputstr: la cadena que se convertirá.

### Ejemplo:

        'Devuelve la cadena «abc\n\tdef\\n»
        MsgBox SF_String.Escape("abc" & Chr(10) & Chr(9) & "def\n")

## ExpandTabs

Replaces Tab characters Chr(9) by space characters to replicate the behavior of tab stops.

Si se encuentra un salto de renglón, se inicia un renglón nuevo y se reinicia el contador de caracteres.

### Sintaxis:

svc.ExpandTabs(inputstr: str, [tabsize: int]): str

### Parámetros:

inputstr: The string to be expanded

tabsize: This parameter is used to determine the Tab stops using the formula: TabSize + 1, 2 * TabSize + 1 , ... N * TabSize + 1 (Default = 8)

### Ejemplo:

        Dim myText as String
        myText = "100" & SF_String.sfTAB & "200" & SF_String.sfTAB & "300" & SF_String.sfNEWLINE & _
                 "X"  & SF_String.sfTAB & "Y" & SF_String.sfTAB & "Z"
        MsgBox SF_String.ExpandTabs(myText)
        '100     200     300
        'X       Y       Z

## FilterNotPrintable

Reemplaza todos los caracteres no imprimibles en la cadena de entrada por un carácter determinado.

### Sintaxis:

svc.FilterNotPrintable(inputstr: str, [replacedby: str]): str

### Parámetros:

inputstr: The string to be searched

replacedby: Zero, one or more characters that will replace all non-printable characters in inputstr (Default = "")

### Ejemplo:

        Dim LF : LF = Chr(10)
        Dim myText as String
        myText = "àén ΣlPµ" & LF & " Русский" & "\n"
        MsgBox SF_String.FilterNotPrintable(myText)
        ' "àén ΣlPµ Русский\n"

## FindRegex

Encuentra en una cadena una subcadena que corresponde a una expresión regular dada.

### Sintaxis:

svc.FindRegex(inputstr: str, regex: str, [start: int], [casesensitive: bool], [forward: bool]): str

### Parámetros:

inputstr: The string to be searched

regex: The regular expression

start: The position in the string where the search will begin. This parameter is passed by reference, so after execution the value of start will point to the first character of the found substring. If no matching substring is found, start will be set to 0.

casesensitive: The search can be case sensitive or not (Default = False).

forward: Determines the direction of the search. If True, search moves forward. If False search moves backwards (Default = True)

At the first iteration, if forward = True, then start should be equal to 1, whereas if forward = False then start should be equal to Len(inputstr)

### Ejemplo:

        Dim lStart As Long : lStart = 1
        Dim result as String
        result = SF_String.FindRegex("abCcdefghHij", "C.*H", lStart, CaseSensitive := True)
        MsgBox lStart & ": " & result
        '3: CcdefghH

In the example above, the new value of lStart can be used to keep searching the same input string by setting the Start parameter to lStart + Len(result) at the next iteration.

## HashStr

Hash functions are used inside some cryptographic algorithms, in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more.

The HashStr method returns the result of a hash function applied on a given string and using a specified algorithm, as a string of lowercase hexadecimal digits.

The hash algorithms supported are: MD5, SHA1, SHA224, SHA256, SHA384 and SHA512.

### Sintaxis:

svc.HashStr(inputstr: str, algorithm: str): str

### Parámetros:

inputstr: The string to hash. It is presumed to be encoded in UTF-8. The hashing algorithm will consider the string as a stream of bytes.

algorithm: One of the supported algorithms listed above, passed as a string.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.HashStr("œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ‘åß∂ƒ©˙∆˚¬", "MD5")
        ' c740ccc2e201df4b2e2b4aa086f35d8a

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        a_string = "œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ‘åß∂ƒ©˙∆˚¬"
        hash_value = svc.HashStr(a_string, "MD5")
        bas.MsgBox(hash_value)
        # c740ccc2e201df4b2e2b4aa086f35d8a

## HtmlEncode

Encodes the input string into the HTML character codes, replacing special characters by their & counterparts.

For example, the character é would be replaced by &eacute; or an equivalent numerical HTML code.

### Sintaxis:

svc.HtmlEncode(inputstr: str): str

### Parámetros:

inputstr: la cadena para codificar.

### Ejemplo:

        MsgBox SF_String.HtmlEncode("<a href=""https://a.b.com"">From α to ω</a>")
        ' "&lt;a href=&quot;https://a.b.com&quot;&gt;From &#945; to &#969;&lt;/a&gt;"

## IsADate

Returns True if the input string is a valid date according to a specified date format.

### Sintaxis:

svc.IsADate(inputstr: str, [dateformat: str]): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False

dateformat: The date format, as a string. It can be either "YYYY-MM-DD" (default), "DD-MM-YYYY" or "MM-DD-YYYY"

El guion (-) puede sustituirse por un punto (.), una barra (/) o un espacio.

If the format is invalid, the method returns False.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsADate("2020-12-31", "YYYY-MM-DD") ' True

This method checks the format of the input string without performing any calendar-specific checks. Hence it does not test the input string for leap years or months with 30 or 31 days. For that, refer to the IsDate built-in function.

The example below shows the difference between the methods IsADate (ScriptForge) and the IsDate (built-in) function.

        Dim myDate as String : myDate = "2020-02-30"
        MsgBox SF_String.IsADate(myDate, "YYYY-MM-DD") 'True
        MsgBox IsDate(myDate) ' False

##### En Python

        svc = CreateScriptService("String")
        s_date = "2020-12-31"
        result = svc.IsADate(s_date) # True

## IsAlpha

Returns True if all characters in the string are alphabetic.

Alphabetic characters are those characters defined in the Unicode Character Database as Letter.

### Sintaxis:

svc.IsAlpha(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsAlpha("àénΣlPµ") ' True
        MsgBox SF_String.IsAlpha("myVar3") ' False

## IsAlphaNum

Returns True if all characters in the string are alphabetic, digits or "_" (underscore). The first character must not be a digit.

### Sintaxis:

svc.IsAlphaNum(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsAlphaNum("_ABC_123456_abcàénΣlPµ") ' True
        MsgBox SF_String.IsAlphaNum("123ABC") ' False

## IsAscii

Returns True if all characters in the string are ASCII characters.

### Sintaxis:

svc.IsAscii(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsAscii("a%?,25") ' True
        MsgBox SF_String.IsAscii("abcàénΣlPµ") ' False

## IsDigit

Returns True if all characters in the string are digits.

### Sintaxis:

svc.IsDigit(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsDigit("123456") ' True
        MsgBox SF_String.IsDigit("_12a") ' False

## IsEmail

Returns True if the string is a valid email address.

### Sintaxis:

svc.IsEmail(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsEmail("first.last@something.org") ' True
        MsgBox SF_String.IsEmail("first.last@something.com.br") ' True
        MsgBox SF_String.IsEmail("first.last@something.123") ' False

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        bas.MsgBox(svc.IsEmail("first.last@something.org")) # True
        bas.MsgBox(svc.IsEmail("first.last@something.com.br")) # True
        bas.MsgBox(svc.IsEmail("first.last@something.123")) # False

## IsFileName

Returns True if the string is a valid filename in a given operating system.

### Sintaxis:

svc.IsFileName(inputstr: str, [osname: str]): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

osname: el nombre del sistema operativo, como una cadena. Puede ser «WINDOWS», «LINUX», «MACOSX» o «SOLARIS».

El valor predeterminado es el sistema operativo actual en el que se ejecuta la secuencia de órdenes.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsFileName("/home/user/Documents/a file name.odt", "LINUX") ' True
        MsgBox SF_String.IsFileName("C:\home\a file name.odt", "LINUX") ' False
        MsgBox SF_String.IsFileName("C:\home\a file name.odt", "WINDOWS") ' True

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        bas.MsgBox(svc.IsFileName("/home/user/Documents/a file name.odt", "LINUX")) # True
        bas.MsgBox(svc.IsFileName(r"C:\home\a file name.odt", "LINUX")) # False
        bas.MsgBox(svc.IsFileName(r"C:\home\a file name.odt", "WINDOWS")) # True

## IsHexDigit

Returns True if all characters in the string are hexadecimal digits.

### Sintaxis:

svc.IsHexDigit(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

Los dígitos hexadecimales pueden estar prefijados con «0x» o «&H».

### Ejemplo:

        MsgBox SF_String.IsHexDigit("&H00FF") ' True
        MsgBox SF_String.IsHexDigit("08AAFF10") ' True
        MsgBox SF_String.IsHexDigit("0x18LA22") ' False

## IsIBAN

Returns True if the string is a valid International Bank Account Number (IBAN). The comparison is not case-sensitive.

### Sintaxis:

svc.IsIBAN(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Devuelve tipo:

True if the string contains a valid IBAN number.

### Ejemplo:

        ' Basic
        MsgBox SF_String.IsIBAN("BR15 0000 0000 0000 1093 2840 814 P2") ' True

        # Python
        result = svc.IsIBAN("BR15 0000 0000 0000 1093 2840 814 P2") # True

## IsIPv4

Returns True if the string is a valid IP(v4) address.

### Sintaxis:

svc.IsIPv4(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsIPv4("192.168.1.50") ' True
        MsgBox SF_String.IsIPv4("192.168.50") ' False
        MsgBox SF_String.IsIPv4("255.255.255.256") ' False

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        bas.MsgBox(svc.IsIPv4("192.168.1.50")) # True
        bas.MsgBox(svc.IsIPv4("192.168.50")) # False
        bas.MsgBox(svc.IsIPv4("255.255.255.256")) # False

## IsLike

Returns True if the whole input string matches a given pattern containing wildcards.

### Sintaxis:

svc.IsLike(inputstr: str, pattern: str, [casesensitive: bool]): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

pattern: la pauta como cadena. Los comodines son:

- «?» representa cualquier carácter único;

- «*» representa cero, uno o varios caracteres.

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsLike("aAbB", "?A*") ' True
        MsgBox SF_String.IsLike("C:\a\b\c\f.odb", "?:*.*") ' True
        MsgBox SF_String.IsLike("name:host", "?*@?*") ' False
        MsgBox SF_String.IsLike("@host", "?*@?*") ' False

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        bas.MsgBox(svc.IsLike("aAbB", "?A*")) # True
        bas.MsgBox(svc.IsLike(r"C:\a\b\c\f.odb", "?:*.*")) # True
        bas.MsgBox(svc.IsLike("name:host", "?*@?*")) # False
        bas.MsgBox(svc.IsLike("@host", "?*@?*")) # False

## IsLower

Returns True if all characters in the string are in lowercase. Non-alphabetic characters are ignored.

### Sintaxis:

svc.IsLower(inputstr: str): bool

### Parámetros:

InputStr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsLower("abc'(-xy4z") ' True
        MsgBox SF_String.IsLower("1234") ' True
        MsgBox SF_String.IsLower("abcDefg") ' False

## IsPrintable

Returns True if all characters in the string are printable.

### Sintaxis:

svc.IsPrintable(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsPrintable("àén ΣlPµ Русский") ' True
        MsgBox SF_String.IsPrintable("First line." & Chr(10) & "Second Line.") ' False

## IsRegex

Returns True if the whole input string matches a given regular expression.

### Sintaxis:

svc.IsRegex(inputstr: str, regex: str, [casesensitive: bool]): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

regex: The regular expression. If empty, the method returns False.

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

            MsgBox SF_String.IsRegex("aAbB", "[A-Za-z]+") ' True
            MsgBox SF_String.IsRegex("John;100", "[A-Za-z]+;[0-9]+") ' True
            MsgBox SF_String.IsRegex("John;100;150", "[A-Za-z]+;[0-9]+") ' False

## IsSheetName

Returns True if the input string is a valid Calc sheet name.

### Sintaxis:

svc.IsSheetName(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsSheetName("1àbc + ""déf""") ' True
        MsgBox SF_String.IsSheetName("[MySheet]") ' False

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        bas.MsgBox(svc.IsSheetName("1àbc + ""déf""")) # True
        bas.MsgBox(svc.IsSheetName("[MySheet]")) # False

A sheet name must not contain the characters [ ] * ? : / \ or the character ' (apostrophe) as first or last character.

## IsTitle

Returns True if the first character of every word is in uppercase and the other characters are in lowercase.

### Sintaxis:

svc.IsTitle(inputstr: str): bool

### Parámetros:

inputstr: la cadena que se comprobará. Si está vacía, el método devuelve False.

### Ejemplo:

        MsgBox SF_String.IsTitle("This Is The Title Of My Book") ' True
        MsgBox SF_String.IsTitle("This is the Title of my Book") ' False
        MsgBox SF_String.IsTitle("Result Number 100") ' True

## IsUpper

Returns True if all characters in the string are in uppercase. Non alphabetic characters are ignored.

### Sintaxis:

svc.IsUpper(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsUpper("ABC'(-XYZ") ' True
        MsgBox SF_String.IsUpper("A Title") ' False

## IsUrl

Returns True if the string is a valid absolute URL (Uniform Resource Locator) address. Only the http, https and ftp protocols are supported.

### Sintaxis:

svc.IsUrl(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

##### En BASIC

        MsgBox SF_String.IsUrl("http://foo.bar/?q=Test%20URL-encoded%20stuff") ' True
        MsgBox SF_String.IsUrl("www.somesite.org") ' False

##### En Python

        svc = CreateScriptService("String")
        bas = CreateScriptService("Basic")
        bas.MsgBox(svc.IsUrl("http://foo.bar/?q=Test%20URL-encoded%20stuff")) # True
        bas.MsgBox(svc.IsUrl("www.somesite.org")) # False

## IsWhitespace

Returns True if all characters in the string are whitespaces

### Sintaxis:

svc.IsWhitespace(inputstr: str): bool

### Parámetros:

inputstr: The string to be checked. If empty, the method returns False.

### Ejemplo:

        MsgBox SF_String.IsWhitespace("    ") ' True
        MsgBox SF_String.IsWhitespace(" " & Chr(9) & Chr(10)) ' True
        MsgBox SF_String.IsWhitespace("") ' False

## JustifyCenter

Devuelve la cadena de entrada centrada.

The leading and trailing white spaces are stripped and the remaining characters are completed left and right up to a specified total length with the character padding.

### Sintaxis:

svc.JustifyCenter(inputstr: str, [length: int], [padding: str]): str

### Parámetros:

inputstr: The string to be center-justified. If empty, the method returns an empty string.

length: The length of the resulting string (default = the length of the input string).

If the specified length is shorter than the center-justified input string, then the returned string is truncated.

padding: The single character to be used as padding (default = the ASCII space " ").

### Ejemplo:

        MsgBox SF_String.JustifyCenter("Title", Length := 11) ' "   Title   "
        MsgBox SF_String.JustifyCenter("    ABCDEF", Padding := "_") ' "__ABCDEF__"
        MsgBox SF_String.JustifyCenter("A Long Title", Length := 5) ' "ong T"

## JustifyLeft

Devuelve la cadena de entrada justificada a la izquierda.

The leading white spaces are stripped and the remaining characters are completed to the right up to a specified total length with the character padding.

### Sintaxis:

svc.JustifyLeft(inputstr: str, [length: int], [padding: str]): str

### Parámetros:

inputstr: The string to be left-justified. If empty, the method returns an empty string.

length: The length of the resulting string (default = the length of the input string).

If the specified length is shorter than the left-justified input string, then the returned string is truncated.

padding: The single character to be used as padding (default = the ASCII space " ").

### Ejemplo:

        MsgBox SF_String.JustifyLeft("Title", Length := 10) ' "Title     "
        MsgBox SF_String.JustifyLeft("    ABCDEF", Padding := "_") ' "ABCDEF____"
        MsgBox SF_String.JustifyLeft("A Long Title", Length := 5) ' "A Lon"

## JustifyRight

Devuelve la cadena de entrada justificada a la derecha.

The leading white spaces are stripped and the remaining characters are completed to the left up to a specified total length with the character padding.

### Sintaxis:

svc.JustifyRight(inputstr: str, [length: int], [padding: str]): str

### Parámetros:

inputstr: The string to be right-justified. If empty, the method returns an empty string.

length: The length of the resulting string (default = the length of the input string).

If the specified length is shorter than the right-justified input string, then the returned string is truncated.

padding: The single character to be used as padding (default = the ASCII space " ").

### Ejemplo:

        MsgBox SF_String.JustifyRight("Title", Length := 10) ' "     Title"
        MsgBox SF_String.JustifyRight("  ABCDEF  ", Padding := "_") ' "____ABCDEF"
        MsgBox SF_String.JustifyRight("A Long Title", Length := 5) ' "Title"

## Quote

Returns the input string enclosed in single or double quotes. Existing quotes are left unchanged, including leading and/or trailing quotes.

### Sintaxis:

svc.Quote(inputstr: str, [quotechar: str]): str

### Parámetros:

inputstr: la cadena que se entrecomillará.

quotechar: puede ser una comilla recta simple (') o doble (") (valor predeterminado).

### Ejemplo:

        MsgBox SF_String.Quote("Text Value")
        ' "Text Value"
        MsgBox SF_String.Quote("Book Title: ""The Arabian Nights""", "'")
        ' 'Book Title: "The Arabian Nights"'

This method can be useful while preparing a string field to be stored in a csv-like file, which requires that text values be enclosed with single or double quotes.

## ReplaceChar

Replaces all occurrences of the characters specified in the Before parameter by the corresponding characters specified in After.

If the length of Before is greater than the length of After, the residual characters in Before are replaced by the last character in After.

### Sintaxis:

svc.ReplaceChar(inputstr: str, before: str, after: str): str

### Parámetros:

inputstr: The input string on which replacements will occur.

before: A string with the characters that will be searched in the input string for replacement.

after: A string with the new characters that will replace those defined in before.

### Ejemplo:

        ' Sustituye caracteres acentuados
        MsgBox SF_String.ReplaceChar("Protégez votre vie privée", "àâãçèéêëîïôöûüýÿ", "aaaceeeeiioouuyy")
        ' "Protegez votre vie privee"
        MsgBox SF_String.ReplaceChar("Protégez votre vie privée", "àâãçèéêëîïôöûüýÿ", "")
        ' "Protgez votre vie prive"
        MsgBox SF_String.ReplaceChar("àâãçèéêëîïôöûüýÿ", "àâãçèéêëîïôöûüýÿ", "aaaceeeeiioouuyy")
        ' "aaaceeeeiioouuyy"

El servicio SF_String proporciona constantes públicas provechosas para su uso con conjuntos de caracteres latinos, como se demuestra en el ejemplo siguiente:

        MsgBox SF_String.ReplaceChar("Protégez votre vie privée", SF_String.CHARSWITHACCENT, SF_String.CHARSWITHOUTACCENT)
        ' "Protegez votre vie privee"

## ReplaceRegex

Sustituye todas las ocurrencias de una expresión regular dada por una cadena nueva.

### Sintaxis:

svc.ReplaceRegex(inputstr: str, regex: str, newstr: str, [casesensitive: bool]): str

### Parámetros:

inputstr: The input string on which replacements will occur.

regex: la expresión regular.

newstr: The replacing string.

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

        MsgBox SF_String.ReplaceRegex("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "[a-z]", "x", CaseSensitive := True)
        ' "Lxxxx xxxxx xxxxx xxx xxxx, xxxxxxxxxxx xxxxxxxxxx xxxx." (each lowercase letter is replaced by "x")
        MsgBox SF_String.ReplaceRegex("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "\b[a-z]+\b", "x", CaseSensitive := False)
        ' "x x x x x, x x x." (each word is replaced by "x")

## ReplaceStr

Reemplaza en una cadena algunas o todas las apariciones de una matriz de cadenas por una matriz de cadenas nuevas.

### Sintaxis:

svc.ReplaceStr(inputstr: str, oldstr: str, newstr: str, [occurrences: int], [casesensitive: bool]): str

### Parámetros:

inputstr: The input string on which replacements will occur.

oldstr: A single string or an array of strings. Zero-length strings are ignored.

newstr: The replacing string or the array of replacing strings.

Si oldstr es una matriz, cada aparición de cualquiera de los elementos en oldstr se sustituye por newstr.

If oldstr and newstr are arrays, replacements occur one by one up to the UBound(newstr).

If oldstr has more entries than newstr, then the residual elements in oldstr are replaced by the last element in newstr.

occurrences: The maximum number of replacements. The default value is 0, meaning that all occurrences will be replaced.

When oldstr is an array, the occurrence parameter is computed separately for each item in the array.

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

        MsgBox SF_String.ReplaceStr("100 xxx 200 yyy", Array("xxx", "yyy"), Array("(1)", "(2)"), CaseSensitive := False)
        ' "100 (1) 200 (2)"
        MsgBox SF_String.ReplaceStr("abCcdefghHij", Array("c", "h"), Array("Y", "Z"), CaseSensitive := False)
        ' "abYYdefgZZij"

## Represent

Returns a string with a readable representation of the argument, truncated at a given length. This is useful mainly for debugging or logging purposes.

Si el parámetro anyvalue es un objeto, lo flanquearán corchetes, «[ ]».

In strings, tabs and line breaks are replaced by \t, \n or \r.

If the final length exceeds the maxlength parameter, the latter part of the string is replaced by " ... (N)" where N is the total length of the original string before truncation.

### Sintaxis:

svc.Represent(anyvalue: any, [maxlength: int]): str

### Parámetros:

anyvalue: The input value to be represented. It can be any value, such as a string, an array, a Basic object, a UNO object, etc.

maxlength: The maximum length of the resulting string. The default value is 0, meaning there is no limit to the length of the resulting representation.

### Ejemplo:

        MsgBox SF_String.Represent("this is a usual string") ' "this is a usual string"
        MsgBox SF_String.Represent("this is a usual string", 15) ' "this i ... (22)"
        MsgBox SF_String.Represent("this is a" & Chr(10) & " 2-lines string") ' "this is a\n 2-lines string"
        MsgBox SF_String.Represent(Empty) ' "[EMPTY]"
        MsgBox SF_String.Represent(Null) ' "[NULL]"
        MsgBox SF_String.Represent(Pi) ' "3.142"
        MsgBox SF_String.Represent(CreateUnoService("com.sun.star.util.PathSettings")) ' "[com.sun.star.comp.framework.PathSettings]"

Observe que la representación de los tipos de datos tales como las matrices y los ejemplares de objetos ScriptForge.Dictionary incluyen tanto el tipo de datos como sus valores:

        ' Un ejemplo con una matriz incorporada de BASIC
        MsgBox SF_String.Represent(Array(1, 2, "Text" & Chr(9) & "here"))
        ' "[ARRAY] (0:2) (1, 2, Text\there)"
        ' Un ejemplo con una matriz de ScriptForge
        Dim aValues as Variant
        aValues = SF_Array.RangeInit(1, 5)
        MsgBox SF_String.Represent(aValues)
        ' "[ARRAY] (0:4) (1.0, 2.0, 3.0, 4.0, 5.0)"
        ' Un ejemplo con un diccionario de ScriptForge
        Dim myDict As Variant : myDict = CreateScriptService("Dictionary")
        myDict.Add("A", 1) : myDict.Add("B", 2)
        MsgBox SF_String.Represent(myDict)
        ' "[Dictionary] ("A":1, "B":2)"

## Reverse

Devuelve la cadena de entrada en orden invertido.

Este método es equivalente a la función StrReverse incorporada en BASIC.

Para utilizar la función StrReverse, la instrucción Option VBASupport 1 debe estar presente en el módulo.

### Sintaxis:

svc.Reverse(inputstr: str): str

### Parámetros:

inputstr: la cadena que se invertirá.

### Ejemplo:

        MsgBox SF_String.Reverse("abcdefghij") ' "jihgfedcba"

## SplitLines

Returns a zero-based array of strings with the lines in the input string. Each item in the array is obtained by splitting the input string at newline characters.

### Sintaxis:

svc.SplitLines(inputstr: str, [keepbreaks: int]): str[0..*]

### Parámetros:

inputstr: la cadena que se dividirá.

keepbreaks: When True, line breaks are preserved in the output array (default = False).

### Ejemplo:

        Dim a as Variant
        a = SF_String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3")
        ' a = Array("Line1", "Line2", "Line3")
        a = SF_String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3" & Chr(10))
        ' a = Array("Line1", "Line2", "Line3", "")
        a = SF_String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3" & Chr(10), KeepBreaks := True)
        ' a = Array("Line1\n", "Line2\r", "Line3\n", "")

## SplitNotQuoted

Divide una cadena en una matriz de elementos utilizando un delimitador especificado.

If a quoted substring contains a delimiter, it is ignored. This is useful when parsing CSV-like records that contain quoted strings.

### Sintaxis:

svc.SplitNotQuoted(inputstr: str, [delimiter: str], [occurrences: int], [quotechar: str]): str[0..*]

### Parámetros:

inputstr: la cadena que se dividirá.

delimiter: A string of one or more characters that will be used as delimiter. The default delimiter is the ASCII space " " character.

occurrences: la cantidad máxima de subcadenas que devolver. El valor predeterminado es 0, lo que significa que no hay límite en el número de cadenas devueltas.

quotechar: bien la comilla recta simple (') o bien la doble (").

### Ejemplo:

##### En BASIC

        arr1 = SF_String.SplitNotQuoted("abc def ghi")
        ' arr1 = Array("abc", "def", "ghi")
        arr2 = SF_String.SplitNotQuoted("abc,""def,ghi""", ",")
        ' arr2 = Array("abc", """def,ghi""")
        arr3 = SF_String.SplitNotQuoted("abc,""def\"",ghi""", ",")
         ' arr3 = Array("abc", """def\"",ghi""")
        arr4 = SF_String.SplitNotQuoted("abc,""def\"",ghi"""",", ",")
        ' arr4 = Array("abc", """def\"",ghi""", "")

##### En Python

        svc = CreateScriptService("String")
        arr1 = svc.SplitNotQuoted('abc def ghi')
        # arr1 = ('abc', 'def', 'ghi')
        arr2 = svc.SplitNotQuoted('abc,"def,ghi"', ",")
        # arr2 = ('abc', '"def,ghi"')
        arr3 = svc.SplitNotQuoted(r'abc,"def\",ghi"', ",")
        # arr3 = ('abc', '"def\\",ghi"')
        arr4 = svc.SplitNotQuoted(r'abc,"def\",ghi"",', ",")
        # arr4 = ('abc', '"def\\",ghi""', '')

Beware of the differences between Basic and Python when representing strings. For example, in Basic two "" characters inside a string are interpreted as a single " character. In Python, strings enclosed with single quotes can contain " characters without having to double them.

## StartsWith

Returns True if the first characters of a string are identical to a given substring.

This method returns False if either the input string or the substring have a length = 0 or when the substring is longer than the input string.

### Sintaxis:

svc.StartsWith(inputstr: str, substring: str, [casesensitive: bool]): bool

### Parámetros:

inputstr: la cadena que se someterá a prueba.

substring: The substring to be searched at the start of inputstr.

casesensitive: The search can be case sensitive or not (Default = False).

### Ejemplo:

        MsgBox SF_String.StartsWith("abcdefg", "ABC") 'True
        MsgBox SF_String.StartsWith("abcdefg", "ABC", CaseSensitive := True) 'False

## TrimExt

Devuelve la cadena de entrada sin los espacios en blanco iniciales y finales.

### Sintaxis:

svc.TrimExt(inputstr: str): str

### Parámetros:

inputstr: la cadena a la que se quitarán los espacios.

### Ejemplo:

        MsgBox SF_String.TrimExt(" Some text.  ") ' "Some text."
        MsgBox SF_String.TrimExt("   ABCDEF" & Chr(9) & Chr(10) & Chr(13) & " ") ' "ABCDEF"

## Unescape

Converts any escaped sequence (\\, \n, \r, \t) in the input string to their corresponding ASCII character.

### Sintaxis:

svc.Unescape(inputstr: str): str

### Parámetros:

inputstr: la cadena que se convertirá.

### Ejemplo:

        MsgBox SF_String.Unescape("abc\n\tdef\\n")
        ' "abc" & Chr(10) & Chr(9) & "def\n"

## Unquote

Quita las comillas rectas simples o dobles que encierran la cadena de entrada.

Esto es útil cuando se analizan registros tipo CSV que contienen cadenas entrecomilladas.

### Sintaxis:

svc.Unquote(inputstr: str, [quotechar: str]): str

### Parámetros:

inputstr: la cadena a la que se le quitarán las comillas.

quotechar: puede ser una comilla recta simple (') o doble (") (valor predeterminado).

### Ejemplo:

        Dim s as String
        ' s = "Algún texto" (sin comillas alrededor)
        s = SF_String.Unquote("""Some text""")
        ' La siguiente cadena no tiene comillas, por lo que permanece sin cambios
        ' s = "Algún texto" (sin modificaciones)
        s = SF_String.Unquote("Some text")
        ' Las comillas dentro de la cadena no se eliminan
        ' s = "The ""true"" meaning" (unchanged)
        s = SF_String.Unquote("The ""true"" meaning")

## Wrap

Convierte la cadena de entrada en una matriz de subcadenas para que cada elemento de la matriz tenga como máximo un número determinado de caracteres.

En la práctica, este método devuelve una matriz indizada a partir de cero de renglones de salida, sin saltos de renglón al final salvo que estos ya existan en la entrada.

Las tabulaciones se expanden utilizando el mismo procedimiento que lleva a cabo el método ExpandTabs.

Los saltos de renglón simbólicos se sustituyen por sus equivalentes en caracteres ASCII.

Si la salida ajustada no tiene contenido, la matriz devuelta queda vacía.

### Sintaxis:

svc.Wrap(inputstr: str, [width: int], [tabsize: int]): str

### Parámetros:

inputstr: la cadena a la que se insertarán saltos automáticos.

width: la cantidad máxima de caracteres en cada renglón (70 de manera predeterminada).

tabsize: Before wrapping the text, the existing TAB Chr(9) characters are replaced with spaces. The argument tabsize defines the TAB stops at TabSize + 1, 2 * TabSize + 1 , ... N * TabSize + 1 (Default = 8).

### Ejemplo:

##### En BASIC

        a = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
        b = SF_String.Wrap(a, 20)
        ' Array("Neque porro ", "quisquam est qui ", "dolorem ipsum quia ", "dolor sit amet, ", "consectetur, ", "adipisci velit...")

##### En Python

        a = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
        b = svc.Wrap(a, 20)
        # ('Neque porro ', 'quisquam est qui ', 'dolorem ipsum quia ', 'dolor sit amet, ', 'consectetur, ', 'adipisci velit...')

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.

Temas relacionados

Servicio ScriptForge.Array

Función String

¡Necesitamos su ayuda!