String¶
Clase String integrada.
Descripción¶
Esta es la clase de string integrada (y la utilizada por GDScript). Soporta Unicode y proporciona todos los medios necesarios para el manejo de las strings. Las strings son contadas como referencia y usan un enfoque de copia sobre escritura, por lo que pasarlas es barato en recursos.
Tutoriales¶
Métodos¶
Descripciones de Métodos¶
Construye una nueva String a partir del bool dado.
Construye un nuevo String a partir del int dado.
Construye una nueva string a partir del float dado.
Construye una nueva string a partir del Vector2 dado.
Construye una nueva String a partir del Rect2 dado.
Construye una nueva String a partir del Vector3 dado.
String String ( Transform2D from )
Construye un nuevo String a partir del dado Transform2D.
Construye una nueva String desde el Plane dado.
Construye una nueva String a partir del Quat dado.
Construye una nueva String a partir del AABB dado.
Construye una nueva String a partir de la Basis dada.
Construye un nuevo String a partir de la Transform dada.
Construye un nuevo String a partir del Color dado.
Construye un nuevo String a partir del NodePath dado.
Construye una nueva String a partir del RID dado.
String String ( Dictionary from )
Construye un nuevo String a partir del Dictionary dado.
Construye un nuevo String a partir del Array dado.
String String ( PoolByteArray from )
Constructs a new String from the given PoolByteArray.
String String ( PoolIntArray from )
Constructs a new String from the given PoolIntArray.
String String ( PoolRealArray from )
Constructs a new String from the given PoolRealArray.
String String ( PoolStringArray from )
Constructs a new String from the given PoolStringArray.
String String ( PoolVector2Array from )
Constructs a new String from the given PoolVector2Array.
String String ( PoolVector3Array from )
Constructs a new String from the given PoolVector3Array.
String String ( PoolColorArray from )
Constructs a new String from the given PoolColorArray.
Devuelve true
si la string comienza con la string dada.
PoolStringArray bigrams ( )
Devuelve los bigramas (pares de letras consecutivas) de esta string.
String c_escape ( )
Devuelve una copia de la string con caracteres especiales escapados usando el estándar del lenguaje C.
String c_unescape ( )
Returns a copy of the string with escaped characters replaced by their meanings. Supported escape sequences are \'
, \"
, \?
, \\
, \a
, \b
, \f
, \n
, \r
, \t
, \v
.
Note: Unlike the GDScript parser, this method doesn't support the \uXXXX
escape sequence.
String capitalize ( )
Cambia el caso de algunas cartas. Reemplaza los subrayados por espacios, añade espacios antes de los caracteres en mayúsculas, convierte todas las letras en minúsculas, luego pone en mayúsculas la primera letra y cada letra que sigue a un espacio. Para capitalize CamelCase mixed_with_underscores
, devolverá Capitalize Camel Case Mixed With Underscores
.
Performs a case-sensitive comparison to another string. Returns -1
if less than, 1
if greater than, or 0
if equal. "less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order.
Behavior with different string lengths: Returns 1
if the "base" string is longer than the to
string or -1
if the "base" string is shorter than the to
string. Keep in mind this length is determined by the number of Unicode codepoints, not the actual visible characters.
Behavior with empty strings: Returns -1
if the "base" string is empty, 1
if the to
string is empty or 0
if both strings are empty.
To get a boolean result from a string comparison, use the ==
operator instead. See also nocasecmp_to.
Devuelve el número de ocurrencias de la substring what
entre las posiciones de from
y to
. Si from
y to
es igual a 0 se utilizará la string completa. Si sólo a
es igual a 0 se usará la substring restante.
Devuelve el número de ocurrencias de la substring what
(ignorando el caso) entre las posiciones de from
y to
. Si from
y to
es igual a 0 se utilizará la string completa. Si sólo a
es igual a 0 se usará la substring restante.
String dedent ( )
Returns a copy of the string with indentation (leading tabs and spaces) removed. See also indent to add indentation.
bool empty ( )
Devuelve true
si la longitud de la string es igual a 0
.
Devuelve true
si la string termina con la string dada.
Borra los caracteres chars
de la string que comienza con position
.
Finds the first occurrence of a substring. Returns the starting position of the substring or -1
if not found. Optionally, the initial search index can be passed.
Note: If you just want to know whether a string contains a substring, use the in
operator as follows:
# Will evaluate to `false`.
if "i" in "team":
pass
Finds the last occurrence of a substring. Returns the starting position of the substring or -1
if not found.
Finds the first occurrence of a substring, ignoring case. Returns the starting position of the substring or -1
if not found. Optionally, the initial search index can be passed.
Formatea la string reemplazando todas las ocurrencias de placeholder
por values
.
String get_base_dir ( )
Si la string es una ruta de archivo válida, devuelve el nombre del directorio base.
String get_basename ( )
Si la string es una ruta de archivo válida, devuelve la ruta de archivo completa sin la extensión.
String get_extension ( )
Returns the extension without the leading period character (.
) if the string is a valid file name or path. If the string does not contain an extension, returns an empty string instead.
print("/path/to/file.txt".get_extension()) # "txt"
print("file.txt".get_extension()) # "txt"
print("file.sample.txt".get_extension()) # "txt"
print(".txt".get_extension()) # "txt"
print("file.txt.".get_extension()) # "" (empty string)
print("file.txt..".get_extension()) # "" (empty string)
print("txt".get_extension()) # "" (empty string)
print("".get_extension()) # "" (empty string)
String get_file ( )
Si la string es una ruta de archivo válida, devuelve el nombre del archivo.
Splits a string using a delimiter
and returns a substring at index slice
. Returns an empty string if the index doesn't exist.
This is a more performant alternative to split for cases when you need only one element from the array at a fixed index.
Example:
print("i/am/example/string".get_slice("/", 2)) # Prints 'example'.
int hash ( )
Hashea la string y devuelve un entero de 32 bits.
int hex_to_int ( )
Convierte una string que contiene un número hexadecimal en un entero. Se espera que las strings hexadecimales lleven el prefijo "0x
", de lo contrario se devuelve 0
.
print("0xff".hex_to_int()) # Imprimir "255"
String http_escape ( )
Escapa (codifica) una string a un formato compatible con la URL. También conocido como 'codificación de URL'.
print("https://example.org/?escaped=" + "Godot Engine:'docs'".http_escape())
String http_unescape ( )
Desvincula (decodifica) una string en formato codificado de URL. También conocido como "decodificación de URL".
print("https://example.org/?escaped=" + "Godot%20Motor%3A%27docs%27".http_unescape())
Convierte el size
representado como número de bytes a un formato legible para el ser humano utilizando un conjunto de unidades de tamaño de datos internacionalizados, a saber: B, KiB, MiB, GiB, TiB, PiB, EiB. Nótese que la siguiente unidad más pequeña es escogida automáticamente para contener como máximo 1024 unidades.
var bytes = 133790307
var size = String.humanize_size(bytes)
print(size) # imprime "127.5 MiB"
Returns a copy of the string with lines indented with prefix
.
For example, the string can be indented with two tabs using "\t\t"
, or four spaces using " "
. The prefix can be any string so it can also be used to comment out strings with e.g. "# "
. See also dedent to remove indentation.
Note: Empty lines are kept empty.
Devuelve una copia de la string con la substring what
insertada en la posición dada.
bool is_abs_path ( )
Si la string es una ruta a un archivo o directorio, devuelve true
si la ruta es absoluta.
bool is_rel_path ( )
Si la string es una ruta a un archivo o directorio, devuelve true
si la ruta es relativa.
Devuelve true
si esta string es una subsecuente de la string dada.
Devuelve true
si esta string es una subsecuente de la string dada, sin considerar el caso.
bool is_valid_filename ( )
Devuelve true
si esta string está libre de caracteres que no están permitidos en los nombres de los archivos, que son:
: / \ ? * " | % < >
bool is_valid_float ( )
Devuelve true
si esta string contiene un real válido.
Devuelve true
si esta string contiene un número hexadecimal válido. Si with_prefix
es true
, entonces la validez del número hexadecimal está determinada por el prefijo 0x
, por ejemplo: 0xDEADC0DE
.
bool is_valid_html_color ( )
Devuelve true
si esta cadena contiene un color válido en notación HTML hexadecimal. Otras notaciones HTML como colores con nombre o colores hsl()
no se consideran válidas por este método y devolverán false
.
bool is_valid_identifier ( )
Devuelve true
si esta string es un identificador válido. Un identificador válido sólo puede contener letras, dígitos y guiones bajos (_
) y el primer carácter no puede ser un dígito.
bool is_valid_integer ( )
Devuelve true
si esta string contiene un entero válido.
bool is_valid_ip_address ( )
Returns true
if this string contains only a well-formatted IPv4 or IPv6 address. This method considers reserved IP addresses such as 0.0.0.0
as valid.
String json_escape ( )
Devuelve una copia de la string con caracteres especiales escapados usando el estándar JSON.
Devuelve un número de caracteres de la izquierda de la string.
int length ( )
Devuelve la cantidad de caracteres de la string.
Returns a copy of the string with characters removed from the left. The chars
argument is a string specifying the set of characters to be removed.
Note: The chars
is not a prefix. See trim_prefix method that will remove a single prefix string rather than a set of characters.
Hace una comparación simple con expresión que distingue entre mayúsculas y minúsculas, en la que "*"
coincide con cero o más caracteres arbitrarios y "?"
coincide con cualquier carácter individual excepto con un punto ("."
).
Hace una simple comparación expresión insensible a las mayúsculas y minúsculas, en la que "*"
coincide con cero o más caracteres arbitrarios y "?"
coincide con cualquier carácter individual excepto con un punto ("."
).
PoolByteArray md5_buffer ( )
Devuelve el hash MD5 de la string como un conjunto de bytes.
String md5_text ( )
Devuelve el hash MD5 de la string como una string.
Performs a case-insensitive natural order comparison to another string. Returns -1
if less than, 1
if greater than, or 0
if equal. "less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters will be converted to uppercase during the comparison.
When used for sorting, natural order comparison will order suites of numbers as expected by most people. If you sort the numbers from 1 to 10 using natural order, you will get [1, 2, 3, ...]
instead of [1, 10, 2, 3, ...]
.
Behavior with different string lengths: Returns 1
if the "base" string is longer than the to
string or -1
if the "base" string is shorter than the to
string. Keep in mind this length is determined by the number of Unicode codepoints, not the actual visible characters.
Behavior with empty strings: Returns -1
if the "base" string is empty, 1
if the to
string is empty or 0
if both strings are empty.
To get a boolean result from a string comparison, use the ==
operator instead. See also nocasecmp_to and casecmp_to.
Performs a case-insensitive comparison to another string. Returns -1
if less than, 1
if greater than, or 0
if equal. "less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters will be converted to uppercase during the comparison.
Behavior with different string lengths: Returns 1
if the "base" string is longer than the to
string or -1
if the "base" string is shorter than the to
string. Keep in mind this length is determined by the number of Unicode codepoints, not the actual visible characters.
Behavior with empty strings: Returns -1
if the "base" string is empty, 1
if the to
string is empty or 0
if both strings are empty.
To get a boolean result from a string comparison, use the ==
operator instead. See also casecmp_to.
Devuelve el código de caracteres en la posición at
.
Formatea un número para tener un número exacto de digits
después del punto decimal.
Formatea un número para tener un número exacto de digits
después del punto decimal.
String percent_decode ( )
Decodificar una string de porcentaje codificado. Ver percent_encode.
String percent_encode ( )
Percent-encodes una string. Codifica los parámetros en una URL enviadon una solicitud HTTP GET (y los cuerpos de form-urlencoded POST requests).
Si la string es un camino, esto concatena file
al final del string como un sub camino. Por ejemplo, "this/is".plus_file("path") == "this/is/path"
.
Devuelve la string original repetida varias veces. El número de repeticiones viene dado por el argumento.
Reemplaza las ocurrencias de una substring que distingue entre mayúsculas y minúsculas con la dada dentro de la string.
Reemplaza las ocurrencias de una substring insensible a las mayúsculas y minúsculas con la dada dentro de la string.
Performs a case-sensitive search for a substring, but starts from the end of the string instead of the beginning.
Performs a case-insensitive search for a substring, but starts from the end of the string instead of the beginning.
Devuelve el lado derecho de la string desde una posición determinada.
PoolStringArray rsplit ( String delimiter, bool allow_empty=true, int maxsplit=0 )
Divide la string por un string de delimiter
y devuelve un array de substrings, empezando por la derecha.
Las divisiones en el array devuelto se ordenan en el mismo orden que la string original, de izquierda a derecha.
Si se especifica maxsplit
, define el número de divisiones a realizar desde la derecha hasta maxsplit
. El valor por defecto de 0 significa que todos los elementos se dividen, dando así el mismo resultado que split.
Ejemplo:
var some_string = "One,Two,Three,Four"
var some_array = some_string.rsplit(",", true, 1)
print(some_array.size()) # Imprime 2
print(some_array[0]) # Imprime "Cuatro"
print(some_array[1]) # Imprime "Three,Two,One"
Returns a copy of the string with characters removed from the right. The chars
argument is a string specifying the set of characters to be removed.
Note: The chars
is not a suffix. See trim_suffix method that will remove a single suffix string rather than a set of characters.
PoolByteArray sha1_buffer ( )
Devuelve el hash SHA-1 de la string como un conjunto de bytes.
String sha1_text ( )
Devuelve el hash del SHA-1 de la string como una string.
PoolByteArray sha256_buffer ( )
Devuelve el hash SHA-256 de la string como un array de bytes.
String sha256_text ( )
Devuelve el hash SHA-256 de la string como una string.
Devuelve el índice de similitud del texto comparado con esta string. 1 significa totalmente similar y 0 significa totalmente diferente.
String simplify_path ( )
Returns a simplified canonical path.
PoolStringArray split ( String delimiter, bool allow_empty=true, int maxsplit=0 )
Splits the string by a delimiter
string and returns an array of the substrings. The delimiter
can be of any length.
If maxsplit
is specified, it defines the number of splits to do from the left up to maxsplit
. The default value of 0
means that all items are split.
If you need only one element from the array at a specific index, get_slice is a more performant option.
Example:
var some_string = "One,Two,Three,Four"
var some_array = some_string.split(",", true, 1)
print(some_array.size()) # Prints 2
print(some_array[0]) # Prints "One"
print(some_array[1]) # Prints "Two,Three,Four"
If you need to split strings with more complex rules, use the RegEx class instead.
PoolRealArray split_floats ( String delimiter, bool allow_empty=true )
Divide la string en reales usando una string delimitadora y devuelve un array de las substrings..
Por ejemplo, "1,2.5,3"
devolverá [1,2.5,3]
si se divide por ","
.
Devuelve una copia de la string despojada de cualquier carácter no imprimible (incluyendo tabulaciones, espacios y saltos de línea) al principio y al final. Los argumentos opcionales se utilizan para conmutar la eliminación de la string en los bordes izquierdo y derecho respectivamente
String strip_escapes ( )
Returns a copy of the string stripped of any escape character. These include all non-printable control characters of the first page of the ASCII table (< 32), such as tabulation (\t
in C) and newline (\n
and \r
) characters, but not spaces.
Devuelve parte de la string de la posición from
con la longitud len
. El argumento len
es opcional y usando -1
devolverá los caracteres restantes de la posición dada.
PoolByteArray to_ascii ( )
Converts the String (which is a character array) to PoolByteArray (which is an array of bytes). The conversion is faster compared to to_utf8, as this method assumes that all the characters in the String are ASCII characters.
float to_float ( )
Convierte una cadena que contiene un número decimal en un float
.
int to_int ( )
Convierte una string que contiene un número entero en un int
.
String to_lower ( )
Devuelve la string convertida en minúsculas.
String to_upper ( )
Devuelve la string convertida en mayúsculas.
PoolByteArray to_utf8 ( )
Converts the String (which is an array of characters) to PoolByteArray (which is an array of bytes). The conversion is a bit slower than to_ascii, but supports all UTF-8 characters. Therefore, you should prefer this function over to_ascii.
PoolByteArray to_wchar ( )
Converts the String (which is an array of characters) to PoolByteArray (which is an array of bytes).
Elimina una determinada string desde el principio si empieza con ella o deja la string sin cambios.
Elimina una determinada string del final si termina con ella o deja la string sin cambios.
String validate_node_name ( )
Removes any characters from the string that are prohibited in Node names (.
:
@
/
"
).
String xml_escape ( )
Devuelve una copia de la string con caracteres especiales escapados usando el estándar XML.
String xml_unescape ( )
Devuelve una copia de la string con los caracteres escapados reemplazados por sus significados según el estándar XML.