String Functions in Scilab

// We alias disp to a shorter name as we'll use it a lot below.
p = disp;

function main()
    // Here's a sample of the string functions available in Scilab.
    // Since these are functions, not methods on the string object itself,
    // we need to pass the string in question as an argument to the function.
    
    p("Contains:  " + string(strindex("test", "es") <> []));
    p("Count:     " + string(length(strindex("test", "t"))));
    p("HasPrefix: " + string(strncmp("test", "te", 2) == 0));
    p("HasSuffix: " + string(strrcmp("test", "st") == 0));
    p("Index:     " + string(strindex("test", "e")));
    p("Join:      " + strcat(["a", "b"], "-"));
    p("Repeat:    " + strcat(repmat("a", 1, 5)));
    p("Replace:   " + strsubst("foo", "o", "0"));
    p("Replace:   " + strsubst("foo", "o", "0", 1));
    p("Split:     " + strcat(tokens("a-b-c-d-e", "-"), " "));
    p("ToLower:   " + convstr("TEST", "l"));
    p("ToUpper:   " + convstr("test", "u"));
end

main();

This script demonstrates various string operations in Scilab, which is similar to the original example. Here’s an explanation of the functions used:

  1. strindex: Finds the starting index of a substring within a string.
  2. length: Returns the length of an array or string.
  3. strncmp: Compares the first n characters of two strings.
  4. strrcmp: Compares two strings from right to left.
  5. strcat: Concatenates strings.
  6. repmat: Repeats a matrix (or string) multiple times.
  7. strsubst: Substitutes substrings within a string.
  8. tokens: Splits a string into an array of substrings based on a delimiter.
  9. convstr: Converts the case of a string (to lower or upper).

Note that Scilab doesn’t have exact equivalents for all the functions in the original example, so some adaptations were made. For instance, Contains is simulated using strindex, and HasPrefix and HasSuffix are implemented using strncmp and strrcmp respectively.

To run this script, save it as string_functions.sce and execute it in Scilab:

--> exec('string_functions.sce', -1)
Contains:  1
Count:     2
HasPrefix: 1
HasSuffix: 1
Index:     2
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     a b c d e
ToLower:   test
ToUpper:   TEST

This output demonstrates the results of various string operations in Scilab, similar to the original example.