XScript Manual · Chapter 30

title: "STR — string utilities" chapter: 30

STR — string functions

STR collects parsing, conversion, and search helpers used constantly for protocol framing, order-number splitting, and recipe parsing.

Basic example

string data = "    abc d   ";
Log("[{0}] => Trim = [{1}]", data, STR.Trim(data));
 
data = "12";
int dataToInt = STR.ParseToInt(data);
 
data = "12.3";
dataToInt = STR.ParseToInt(data, 0);
 
data = "abc:123";
string name;
string value;
STR.ParseNameValue(data, name, value, ":");
 
int pos = STR.IndexOf(data, ":");
string tail = STR.Substring(data, pos + 1);

Real-world — recipe parsing

// recipe = "1:50,3:20.3,7:60.1"
array items = STR.ParseCommaString(recipe);
 
if (items.Count == 0)
{
    return -1;
}
 
int unitNo;
double target;
 
for (i, 0, items.Count - 1)
{
    if (STR.ParsePairIntDouble(items[i], unitNo, target, ":") == false)
    {
        return -1;
    }
    if (unitNo == targetUnit)
    {
        return target;
    }
}

Key methods

Basics

SignatureDescription
int Length(string text)Length
string Trim(string text)Trim whitespace
string ToUpper(string text) / string ToLower(string text)Case
string Replace(string text, string oldValue, string newValue)Replace
bool IsNullOrWhiteSpace(string text)Empty / whitespace
bool Contains(string text, string value)Contains
bool StartsWith(string text, string value) / EndsWithPrefix / suffix

Search / extract

SignatureDescription
int IndexOf(string text, string value)First index
int IndexOf(string text, string value, int startIndex)From index
int NthIndexOf(string text, string value, int n)Nth occurrence
string Substring(string text, int startIndex)To end
string Substring(string text, int startIndex, int length)Fixed length

Parsing

SignatureDescription
array ParseCommaString(string commaString)CSV split
array ParseSplitString(string text, string splitString)Custom delimiter
bool ParseNameValue(string text, ref string name, ref string value, string delim)name/value pair
bool ParsePairIntDouble(string text, ref int first, ref double second, string delim)key:value int + double
bool ParsePairStrings(string text, ref string first, ref string second)String pair
int ParseToInt(string text) / with defaultTo int
double ParseToDouble(string text) / with defaultTo double

File

SignatureDescription
array ReadAllLines(string path, bool addLog = true)File → lines

Tips

  • For external protocols, two-stage parsing (ParseCommaString then ParsePairIntDouble / ParsePairStrings) is robust.
  • ParseToInt with a default argument is the safe form — no exception on bad input.
  • $"..." interpolation is usually clearer than FormatString; use SYS.GetDateTimeStringFormat for complex locale/date formatting.