StringBuilder Rust Reference Documentation
StringBuilder
Current Version: 11.6.1
Chilkat.StringBuilder
Append strings, characters, integers, random values, UUIDs, encoded data,
and other Chilkat objects without repeatedly recreating strings.
Find substrings, compare content, extract ranges, split or inspect text,
and work with selected portions of the buffer.
Replace text, mask sensitive values, normalize line endings, trim or edit
content, and apply regex-based processing when needed.
Encode or decode text and binary data using formats such as Base64, hex,
URL encoding, quoted-printable, and other supported encodings.
Compute hashes of the current text, convert Markdown to HTML, and move
content between
Load text from files, save text with explicit character encodings, and
securely clear the buffer when it contains sensitive data.
For an extended overview, see
StringBuilder Class Overview.
Build, transform, search, encode, decode, hash, and save mutable text.
Chilkat.StringBuilder is a flexible mutable text container for
constructing and transforming strings. It supports appending text, integers,
random values, UUIDs, encoded bytes, and BinData; searching,
comparing, extracting, replacing, masking, regex processing, line-ending
normalization, encoding, decoding, hashing, Markdown conversion, file I/O,
and secure clearing of sensitive text.
Build text incrementally
Search and extract
Replace and transform
Encoding and decoding
Hashing and conversion
StringBuilder, BinData, files,
and plain strings.
File I/O and secure clearing
StringBuilder when text will be assembled or modified in
multiple steps. Append or load the starting content, perform searches,
replacements, encoding, decoding, hashing, or line-ending normalization, then
retrieve the result as a string, save it to a file, or pass the object
directly to another Chilkat method.
Object Creation
// Cargo.toml:
// [dependencies]
// chilkat = "11.6"
use chilkat::StringBuilder;
// Once per process, before any other Chilkat call:
chilkat::unlock_bundle("Anything for 30-day trial")?; // shorthand for Global::new().unlock_bundle(..)
let string_builder = StringBuilder::new();
// ... the native object is freed when `string_builder` goes out of scope.Creates the underlying native Chilkat object (StringBuilder also implements Default). Every method takes &self, so the object never needs to be declared mut. A StringBuilder is Send but not Sync: it may be moved to another thread, but a reference to it cannot be shared between threads at the same time.
The native object is freed when the StringBuilder is dropped — when it goes out of scope, or explicitly with drop(string_builder). There is no Dispose method to call.
Errors
Methods that can fail return chilkat::Result<T>, which is Result<T, chilkat::Error>: a method whose only outcome is success or failure returns Result<()>, a method producing a string or an object returns Result<String> or Result<StringBuilder>. The error carries the object's LastErrorText at the time of the failure (Error::last_error_text), the class and method names, and implements std::error::Error, so ? works in any function returning chilkat::Result or a Box<dyn Error>. Properties never fail, and methods that answer a question (has_..., is_..., ...) return a plain bool.
match string_builder.some_method(...) {
Ok(value) => println!("{value:?}"),
Err(e) => eprintln!("{}", e.last_error_text()),
}
Properties
DebugLogFilePath
pub fn debug_log_file_path(&self) -> String
pub fn set_debug_log_file_path(&self, value: &str)
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
HasEmojis
pub fn has_emojis(&self) -> bool
Returns true if the content contains one or more emoji characters.
IntValue
pub fn int_value(&self) -> i32
pub fn set_int_value(&self, value: i32)
Returns the content of the string converted to an integer.
topIsBase64
pub fn is_base64(&self) -> bool
Returns true if the content contains only those characters allowed in the base64 encoding. A base64 string is composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/' and it is often padded at the end with up to two '=', to make the length a multiple of 4. Whitespace is ignored.
LastErrorHtml
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
pub fn last_method_success(&self) -> bool
pub fn set_last_method_success(&self, value: bool)
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
Length
pub fn length(&self) -> i32
The number of characters of the string contained within this instance.
topVerboseLogging
pub fn verbose_logging(&self) -> bool
pub fn set_verbose_logging(&self, value: bool)
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
Methods
Append
Appends a copy of the specified string to this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendBd
Appends the contents of bin_data. The charset specifies the character encoding of the bytes contained in bin_data. The charset can be any of the supported encodings listed at Chilkat Supported Character Encodings. To append the entire contents of bin_data, set offset and num_bytes equal to zero. To append a range of bin_data, set the offset and num_bytes to specify the range.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendInt
Appends the string representation of a specified 32-bit signed integer to this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendInt64
Appends the string representation of a specified 64-bit signed integer to this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendLine
Appends the str followed by a CRLF or LF to the end of the curent StringBuilder object. If crlf is true, then a CRLF line ending is used. Otherwise a LF line ending is used.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendLn
Appends the str followed by a CRLF to the end of this object. This method is the same as AppendLine , except the line-ending is always CRLF.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendRandom
Append num_bytes random bytes encoded according to encoding. encoding can be hex, hex_lower, base64, base64url, or any other encoding supported by Chilkat.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendSb
Appends the contents of another StringBuilder to this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendUuid
Generates and appends a random GUID/UUID such as 63c35f38-2b5f-4600-b3da-3ddee86d62b3. If lower_case is true, then the hex values use lowercase (a - f). If lower_case is false then uppercase is used (A - F).
Note: This generates a version 4 UUID.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AppendUuid7
Generates and appends a random version 7 UUID. If lower_case is true, then the hex values use lowercase (a - f). If lower_case is false then uppercase is used (A - F).
Returns Ok(()) for success, Err(chilkat::Error) for failure.
Clear
Removes all characters from the current StringBuilder instance.
topContains
Returns true if the str is contained within this object. For case sensitive matching, set case_sensitive equal to true. For case-insensitive, set case_sensitive equal to false.
ContainsWord
Returns true if the word is contained within this object, but only if it is a whole word. This method is limited to finding whole words in strings that only contains characters in the Latin1 charset (i.e. iso-8859-1 or Windows-1252). A whole word can only contain alphanumeric chars where the alpha chars are restricted to those of the Latin1 alpha chars. (The underscore character is also considered part of a word.)
For case sensitive matching, set case_sensitive equal to true. For case-insensitive, set case_sensitive equal to false.
ContentsEqual
Returns true if the contents of this object equals the str. Returns false if unequal. For case insensitive equality, set case_sensitive equal to false.
ContentsEqualSb
Returns true if the contents of this object equals the sb. Returns false if unequal. For case insensitive equality, set case_sensitive equal to false.
Decode
Decodes and replaces the contents with the decoded string. The encoding can be set to any of the following strings: base64, hex, quoted-printable (or qp), url, base32, Q, B, url_rc1738, url_rfc2396, url_rfc3986, url_oauth, uu, modBase64, or html (for HTML entity encoding). The full up-to-date list of supported binary encodings is available at the link entitled Supported Binary Encodings below.
Note: This method can only be called if the encoded content decodes to a string. The charset indicates the charset to be used in intepreting the decoded bytes. For example, the charset can be utf-8, utf-16, iso-8859-1, shift_JIS, etc.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
DecodeAndAppend
Decodes a binary encoded string, where the binary encoding (such as url, hex, base64, etc.) is specified by encoding, and the underlying charset encoding (such as utf-8, windows-1252, etc.) is specified by charset. The decoded string is appended to this object.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
Encode
Encodes to base64, hex, quoted-printable, URL encoding, etc. The encoding can be set to any of the following strings: base64, hex, quoted-printable (or qp), url, base32, Q, B, url_rc1738, url_rfc2396, url_rfc3986, url_oauth, uu, modBase64, or html (for HTML entity encoding). The full up-to-date list of supported binary encodings is available at the link entitled Supported Binary Encodings below.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
EndsWith
Returns true if the string ends with substr. Otherwise returns false. The comparison is case sensitive if case_sensitive is true, and case insensitive if case_sensitive is false.
EntityDecode
Decodes HTML entities. See HTML entities for more information about HTML entities.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
GetAfterBetween
Begin searching after the 1st occurrence of search_after is found, and then return the substring found between the next occurrence of begin_mark and the next occurrence of end_mark.
Returns Err(chilkat::Error) on failure.
GetAfterFinal
Returns the substring found after the final occurrence of marker. If remove_flag is true, the marker and the content that follows is removed from this content.
If the marker is not present, then the entire string is returned. In this case, if remove_flag is true, this object is also cleared.
Returns Err(chilkat::Error) on failure.
GetAsString
GetBefore
Returns the substring found before the 1st occurrence of marker. If remove_flag is true, the content up to and including the marker is removed from this object's contents.
If the marker is not present, then the entire string is returned. In this case, if remove_flag is true, this object is also cleared.
Returns Err(chilkat::Error) on failure.
GetBetween
Returns the substring found between the 1st occurrence of begin_mark and the next occurrence of end_mark.
Returns Err(chilkat::Error) on failure.
GetEncoded
Returns the string contents encoded in an encoding such as base64, hex, quoted-printable, or URL-encoding. The encoding can be set to any of the following strings: base64, hex, quoted-printable (or qp), url, base32, Q, B, url_rc1738, url_rfc2396, url_rfc3986, url_oauth, uu, modBase64, or html (for HTML entity encoding). The full up-to-date list of supported binary encodings is available at the link entitled Supported Binary Encodings below.
Note: The Encode method modifies the content of this object. The GetEncoded method leaves this object's content unmodified.
Returns Err(chilkat::Error) on failure.
GetHash
Returns the hash of the contents of this object. The algorithm is the hash algorithm, and can be sha1, sha256, sha384, sha512, sha3-224, sha3-256, sha3-384, sha3-512, md2, md5, ripemd128, ripemd160,ripemd256, or ripemd320.
The encoding can be base64, modBase64, base64Url, base32, base58, qp (for quoted-printable), url (for url-encoding), hex, hexLower, or any of the encodings found at Chilkat Binary Encodings List.
The charset is the character encoding byte representation to hash. It is typically utf-8. It can be any of the chacter encodings listed at Chilkat Character Encodings List.
Returns Err(chilkat::Error) on failure.
GetNth
Returns the Nth substring in string that is a list delimted by delimiter_char. The first substring is at index 0. If except_double_quoted is true, then the delimiter char found between double quotes is not treated as a delimiter. If except_escaped is true, then an escaped (with a backslash) delimiter char is not treated as a delimiter.
Returns Err(chilkat::Error) on failure.
GetRange
Returns a string containing the specified range of characters from this instance. If remove_flag is true, then the range of chars is removed from this instance.
Note: It was discovered that the range of chars was always removed regardless of the value of remove_flag. This is fixed in v9.5.0.89.
Returns Err(chilkat::Error) on failure.
GetRangeSb
Appends to start_index the specified range of characters from this instance. If remove_flag is true, then the range of chars is removed from this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
IsWellFormed
Returns true if the contents of this object are well-formed JSON or XML. format selects which check to apply and must be json or xml (case insensitive). Returns false if the contents do not conform, or if format is anything else.
Chilkat's JSON and XML parsers are deliberately tolerant. Given text that is not well-formed they can still report success, leaving an empty or partially populated document. This method answers the question those parsers do not, and it does so without loading the text into a JsonObject or Xml object first. The checks applied here are the same ones those classes apply when their Strict property is set.
For xml this is a well-formedness check: element nesting and tag matching, attribute syntax and duplicate attributes, entity and character references, comments, processing instructions, CDATA sections, the XML declaration, the DOCTYPE declaration, and that the bytes are valid UTF-8 containing only characters XML permits. It is not a validating parse: no DTD or schema is read.
For json the full RFC 8259 grammar is checked.
Empty contents are not well-formed in either format, so false is returned.
LastNLines
Returns the last N lines of the text. If fewer than num_lines lines exists, then all of the text is returned. If b_crlf is true, then the line endings of the returned string are converted to CRLF, otherwise the line endings are converted to LF-only.
Returns Err(chilkat::Error) on failure.
LoadFile
Loads the contents of a file.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
MarkdownToHtml
This method converts the Markdown content of this object to HTML, storing the result in sb_html. It supports both streaming and full document conversion. options specifies conversion options, including a key streaming option. In streaming mode, generated HTML is appended to sb_html. In non-streaming mode, sb_html is fully replaced by the generated HTML. For further details, see the examples linked below.
In streaming mode, only complete markdown lines are converted to HTML and removed from this object, leaving just the final partial line, if present. If this object contains only a partial markdown line, no HTML is emitted.
Starting in v11.3.0 ...
"emitJavascript": truecan be included inoptionsto emit Javascript function calls instead of HTML. This is used to update the response in an embedded browser in real-time. See Real-Time Streaming AI Responses to Embedded Browsers in Desktop Apps"streamingShell": trueis used to convert an empty string to an HTML shell to be used as the starting point before applying Javascript function calls. See Preparing the HTML Shell"theme": "html_theme_name"can be included when creating the HTML shell to select a predefined theme or when converting Markdown to HTML in non-streaming mode. The available themes are:- ChatGPT - A style that is similar to the ChatGPT application.
- cleanWin - A clean style for Windows applications.
- cleanMac - A clean style for MacOS applications.
- raw - No HTML styles, header, or body begin/end elements are emitted. Only the Markdown to HTML generated elements are emitted.
If no
themeis is included, then default HTML docType/root/body/header elements are emitted unless various parts are overridden bydocType,rootElement,head,bodyStart,bodyEnd, andbodyExtra."usesPrism": truecan be included when creating the HTML shell (or when converting Markdown to HTML in non-streaming mode) to include PRISM code highlighting."prism": { "theme": "prism_theme_name" }Is optional and can be used to specify the prism theme whenusesPrismistrue. Possible values are:- tomorrow
- default
- coy
- dark
- funky
- okaidia
- solarizedlight
- twilight
"prism": { "version": "version_number" }Is optional can can be used to specify the prism version, such as"1.29.0"whenusesPrismistrue. If not specified, then "1.29.0" is used.- If no
themeis specified, then any or all of the following HTML document parts can be explicitly specified:"docType": "doctype_element"TheDOCTYPEelement. The default is"<!DOCTYPE html>""rootElement": "root_element"Thehtmlelement. The default is"<html>""head": "head_section"The HTML fragment for the HTML head section. The default is"<head><meta charset="utf-8" /></head>".
Note: IfusesPrismistrue, then prism related links will be inserted just before the</head>."bodyStart": "html_fragment"The HTML fragment to begin the body section. The default is"<body><div id="content">""bodyEnd": "html_fragment"The HTML fragment to end the body section. The default is"</div><!-- end-of-content-div --></body>""noContentDiv": trueIf set, the default bodyStart and bodyEnd do not include the"<div id="content">"and"</div><!-- end-of-content-div -->"
"copyButton": trueIn non-streaming mode, can optionally be set to include HTML for adding a copy button. THe copy button is added by default in streaming mode."ChatGPT": { "max-width": "css_length"; }Is optional can can be used to specify the max width of the body text if thethemeisChatGPT. The css_length is a length using CSS length units, such as"72ch","40em","800px", etc.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
MaskQuotedStrings
This function masks the content inside single and/or double-quoted strings by replacing it with a specified mask character (mask_char). The content of each masked quoted string is saved to masked_strings. The contents can be restored by calling RestoreMaskedStrings.
quote_type determines which types of quoted strings are masked:
- Both single and double quoted.
- Only single quoted strings.
- Only double quoted strings.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
Obfuscate
Obfuscates the string. (The Unobfuscate method can be called to reverse the obfuscation to restore the original string.)
The Chilkat string obfuscation algorithm works by taking the utf-8 bytes of the string, base64 encoding it, and then scrambling the letters of the base64 encoded string. It is deterministic in that the same string will always obfuscate to the same result. It is NOT a secure way of encrypting a string. It is only meant to be a simple means of transforming a string into something unintelligible.
Prepend
Prepends a copy of the specified string to this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
PunyDecode
In-place decodes the string from punycode.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
PunyEncode
In-place encodes the string to punycode.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RegexMatch
Searches the content of this object for substrings that match a regular expression pattern and returns the matches in json. Returns the number of matches or -1 for failure. timeout_ms is the maximum number of milliseconds of processing allowed before giving up. Pass 0 for an infinite amount of time. Failure information is also returned in json.
RegexReplace
Replaces the substrings of capture groups found in a previous call to RegexMatch.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveAccents
Removes the accents (diacritics) from European accented characters. This applies only to the accented characters found in the Windows-1252 (Latin alphabet) and Windows-1250 (Central European) charsets. Accent marks for characters in other languages will not be removed.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveAfterFinal
Removes the substring found after the final occurrence of the marker. Also removes the marker. Returns true if the marker was found and content was removed. Otherwise returns false.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveBefore
Removes the substring found before the 1st occurrence of the marker. Also removes the marker. Returns true if the marker was found and content was removed. Otherwise returns false.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveCharsAt
Removes the specified range of characters from this instance.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveEmojis
Removes all emoji characters from the string.
topReplace
Replaces all occurrences of a specified string in this instance with another specified string. Returns the number of replacements.
topReplaceAfterFinal
Replaces the content found after the final occurrence of marker with replacement.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ReplaceAllBetween
Replaces the first occurrence of ALL the content found between begin_mark and end_mark with replacement. The begin_mark and end_mark are included in what is replaced if replace_marks is true.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ReplaceBetween
Replaces all occurrences of value with replacement, but only where value is found between begin_mark and end_mark. Returns the number of replacements made.
ReplaceFirst
Replaces the first occurrence of a specified string in this instance with another string. Returns true if the value was found and replaced. Otherwise returns false.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ReplaceI
Replaces all occurrences of value with the decimal integer replacement. Returns the number of replacements.
ReplaceNoCase
Replaces all occurrences of value with replacement (case insensitive). Returns the number of replacements.
ReplaceWord
Replaces all word occurrences of a specified string in this instance with another specified string. Returns the number of replacements made.
Important: This method is limited to replacing whole words in strings that only contains characters in the Latin1 charset (i.e. iso-8859-1 or Windows-1252). A whole word can only contain alphanumeric chars where the alpha chars are restricted to those of the Latin1 alpha chars. (The underscore character is also considered part of a word.)
RestoreMaskedStrings
Restores single and/or double-quoted strings previously masked by MaskQuotedStrings.
quote_type determines which types of quoted strings are masked:
- Both single and double quoted.
- Only single quoted strings.
- Only double quoted strings.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SecureClear
Removes all characters from the current StringBuilder instance, and write zero bytes to the allocated memory before deallocating.
topSetNth
Sets the Nth substring in string in a list delimted by delimiter_char. The first substring is at index 0. If except_double_quoted is true, then the delimiter char found between double quotes is not treated as a delimiter. If except_escaped is true, then an escaped (with a backslash) delimiter char is not treated as a delimiter.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetString
Sets this instance to a copy of the specified string.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
Shorten
Shortens the string by removing the last num_chars chars.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
StartsWith
Returns true if the string starts with substr. Otherwise returns false. The comparison is case sensitive if case_sensitive is true, and case insensitive if case_sensitive is false.
ToCRLF
Converts line endings to CRLF (Windows) format.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ToLF
Converts line endings to LF-only (UNIX) format.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ToLowercase
ToUppercase
Trim
Trims whitespace from both ends of the string.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
TrimInsideSpaces
Replaces all tabs, CR's, and LF's, with SPACE chars, and removes extra SPACE's so there are no occurances of more than one SPACE char in a row.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
Unobfuscate
Unobfuscates the string.
The Chilkat string obfuscation algorithm works by taking the utf-8 bytes of the string, base64 encoding it, and then scrambling the letters of the base64 encoded string. It is deterministic in that the same string will always obfuscate to the same result. It is not a secure way of encrypting a string. It is only meant to be a simple means of transforming a string into something unintelligible.
WriteFile
Writes the contents to a file. If emit_bom is true, then the BOM (also known as a preamble), is emitted for charsets that define a BOM (such as utf-8, utf-16, utf-32, etc.)
Returns Ok(()) for success, Err(chilkat::Error) for failure.
WriteFileIfModified
Writes the contents to a file, but only if it is a new file or if the contents are different than the existing file. If emit_bom is true, then the BOM (also known as a preamble), is emitted for charsets that define a BOM (such as utf-8, utf-16, utf-32, etc.)
Returns Ok(()) for success, Err(chilkat::Error) for failure.