Merge pull request #1151 from revarbat/revarbat_dev

Synopses, etc for strings.scad
This commit is contained in:
Revar Desmera 2023-04-28 19:23:47 -07:00 committed by GitHub
commit fdbecb5f9b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -12,15 +12,18 @@
// Section: Extracting substrings
// Function: substr()
// Synopsis: Returns a substring from a string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// newstr = substr(str, [pos], [len]);
// Description:
// Returns a substring from a string start at position `pos` with length `len`, or
// if `len` isn't given, the rest of the string.
// Returns a substring from a string start at position `pos` with length `len`, or
// if `len` isn't given, the rest of the string.
// Arguments:
// str = string to operate on
// pos = starting index of substring, or vector of first and last position. Default: 0
// len = length of substring, or omit it to get the rest of the string. If len is zero or less then the emptry string is returned.
// len = length of substring, or omit it to get the rest of the string. If len is zero or less then the emptry string is returned.
// Example:
// substr("abcdefg",3,3); // Returns "def"
// substr("abcdefg",2); // Returns "cdefg"
@ -32,12 +35,15 @@ function substr(str, pos=0, len=undef) =
len == undef ? _substr(str, pos, len(str)-pos) :
_substr(str,pos,len);
function _substr(str,pos,len,substr="") =
function _substr(str,pos,len,substr="") =
len <= 0 || pos>=len(str) ? substr :
_substr(str, pos+1, len-1, str(substr, str[pos]));
// Function: suffix()
// Synopsis: Returns the last few characters of a string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// newstr = suffix(str,len);
// Description:
@ -55,6 +61,9 @@ function suffix(str,len) =
// Function: str_find()
// Synopsis: Finds a substring in a string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// ind = str_find(str,pattern,[last=],[all=],[start=]);
// Description:
@ -69,7 +78,7 @@ function suffix(str,len) =
// pattern = string pattern to search for
// ---
// last = set to true to return the last match. Default: false
// all = set to true to return all matches as a list. Overrides last. Default: false
// all = set to true to return all matches as a list. Overrides last. Default: false
// start = index where the search starts
// Example:
// str_find("abc123def123abc","123"); // Returns 3
@ -93,12 +102,12 @@ function str_find(str,pattern,start=undef,last=false,all=false) =
last? _str_find_last(str,pattern,start) :
_str_find_first(str,pattern,len(str)-len(pattern),start);
function _str_find_first(str,pattern,max_sindex,sindex) =
function _str_find_first(str,pattern,max_sindex,sindex) =
sindex<=max_sindex && !substr_match(str,sindex, pattern)?
_str_find_first(str,pattern,max_sindex,sindex+1) :
(sindex <= max_sindex ? sindex : undef);
function _str_find_last(str,pattern,sindex) =
function _str_find_last(str,pattern,sindex) =
sindex>=0 && !substr_match(str,sindex, pattern)?
_str_find_last(str,pattern,sindex-1) :
(sindex >=0 ? sindex : undef);
@ -108,13 +117,16 @@ function _str_find_all(str,pattern) =
[for(i=[0:1:len(str)-len(pattern)]) if (substr_match(str,i,pattern)) i];
// Function: substr_match()
// Synopsis: Returns true if the string `pattern` matches the string `str`.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage
// bool = substr_match(str,start,pattern);
// Description:
// Returns true if the string `pattern` matches the string `str` starting
// at `str[start]`. If the string is too short for the pattern, or
// `start` is out of bounds---either negative or beyond the end of the
// string---then substr_match returns false.
// `start` is out of bounds either negative or beyond the end of the
// string then substr_match returns false.
// Arguments:
// str = String to search
// start = Starting index for search in str
@ -130,7 +142,7 @@ function _str_find_all(str,pattern) =
//
// This is carefully optimized for speed. Precomputing the length
// cuts run time in half when the string is long. Two other string
// comparison methods were slower.
// comparison methods were slower.
function substr_match(str,start,pattern) =
len(str)-start <len(pattern)? false
: _substr_match_recurse(str,start,pattern,len(pattern));
@ -142,11 +154,14 @@ function _substr_match_recurse(str,sindex,pattern,plen,pindex=0,) =
// Function: starts_with()
// Synopsis: Returns true if the string starts with a given substring.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// bool = starts_with(str,pattern);
// Description:
// Returns true if the input string `str` starts with the specified string pattern, `pattern`.
// Otherwise returns false.
// Otherwise returns false.
// Arguments:
// str = String to search.
// pattern = String pattern to search for.
@ -158,11 +173,14 @@ function starts_with(str,pattern) = substr_match(str,0,pattern);
// Function: ends_with()
// Synopsis: Returns true if the string ends with a given substring.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// bool = ends_with(str,pattern);
// Description:
// Returns true if the input string `str` ends with the specified string pattern, `pattern`.
// Otherwise returns false.
// Otherwise returns false.
// Arguments:
// str = String to search.
// pattern = String pattern to search for.
@ -175,6 +193,9 @@ function ends_with(str,pattern) = substr_match(str,len(str)-len(pattern),pattern
// Function: str_split()
// Synopsis: Splits a longer string wherever a given substring occurs.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// string_list = str_split(str, sep, [keep_nulls]);
// Description:
@ -184,9 +205,9 @@ function ends_with(str,pattern) = substr_match(str,len(str)-len(pattern),pattern
// .
// If sep is a single string then each character in sep is treated as a delimiting character and the input string is
// split at every delimiting character. Empty strings can occur whenever two delimiting characters are sequential.
// If sep is a list of strings then the input string is split sequentially using each string from the list in order.
// If sep is a list of strings then the input string is split sequentially using each string from the list in order.
// If keep_nulls is true then the output will have length equal to `len(sep)+1`, possibly with trailing null strings
// if the string runs out before the separator list.
// if the string runs out before the separator list.
// Arguments:
// str = String to split.
// sep = a string or list of strings to use for the separator
@ -225,6 +246,9 @@ function _remove_empty_strs(list) =
// Function: str_join()
// Synopsis: Joints a list of strings into a single string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// str = str_join(list, [sep]);
// Description:
@ -244,6 +268,9 @@ function str_join(list,sep="",_i=0, _result="") =
// Function: str_strip()
// Synopsis: Strips given leading and trailing characters from a string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// str = str_strip(s,c,[start],[end]);
// Description:
@ -287,13 +314,16 @@ function str_strip(s,c,start,end) =
// Function: str_pad()
// Synopsis: Pads a string to a given length.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// padded = str_pad(str, length, char, [left]);
// Description:
// Pad the given string `str` with to length `length` with the specified character,
// which must be a length 1 string. If left is true then pad on the left, otherwise
// pad on the right. If the string is longer than the specified length the full string
// is returned unchanged.
// is returned unchanged.
// Arguments:
// str = string to pad
// length = length to pad to
@ -311,11 +341,14 @@ function str_pad(str,length,char=" ",left=false) =
// Function: str_replace_char()
// Synopsis: Replace given chars in a string with another substring.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip()
// Usage:
// newstr = str_replace_char(str, char, replace);
// Description:
// Replace every occurence of `char` in the input string with the string `replace` which
// can be any string.
// can be any string.
function str_replace_char(str,char,replace) =
assert(is_str(str))
assert(is_str(char) && len(char)==1, "Search pattern 'char' must be a single character string")
@ -324,6 +357,9 @@ function str_replace_char(str,char,replace) =
// Function: downcase()
// Synopsis: Lowercases all characters in a string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip(), upcase(), downcase()
// Usage:
// newstr = downcase(str);
// Description:
@ -338,6 +374,9 @@ function downcase(str) =
// Function: upcase()
// Synopsis: Uppercases all characters in a string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip(), upcase(), downcase()
// Usage:
// newstr = upcase(str);
// Description:
@ -354,6 +393,9 @@ function upcase(str) =
// Section: Random strings
// Function: rand_str()
// Synopsis: Create a randomized string.
// Topics: Strings
// See Also: suffix(), str_find(), substr_match(), starts_with(), ends_with(), str_split(), str_join(), str_strip(), upcase(), downcase()
// Usage:
// str = rand_str(n, [charset], [seed]);
// Description:
@ -361,8 +403,8 @@ function upcase(str) =
// characters of the random string are drawn from that list, weighted by the number
// of times each character appears in the list. If you do not give a character set
// then the string is generated with characters ranging from 0 to z (based on
// character code).
function rand_str(n, charset, seed) =
// character code).
function rand_str(n, charset, seed) =
is_undef(charset)? str_join([for(c=rand_int(48,122,n,seed)) chr(c)])
: str_join([for(i=rand_int(0,len(charset)-1,n,seed)) charset[i]]);
@ -371,12 +413,15 @@ function rand_str(n, charset, seed) =
// Section: Parsing strings into numbers
// Function: parse_int()
// Synopsis: Parse an integer from a string.
// Topics: Strings
// See Also: parse_int(), parse_float(), parse_frac(), parse_num()
// Usage:
// num = parse_int(str, [base])
// Description:
// Converts a string into an integer with any base up to 16. Returns NaN if
// Converts a string into an integer with any base up to 16. Returns NaN if
// conversion fails. Digits above 9 are represented using letters A-F in either
// upper case or lower case.
// upper case or lower case.
// Arguments:
// str = String to convert.
// base = Base for conversion, from 2-16. Default: 10
@ -392,7 +437,7 @@ function rand_str(n, charset, seed) =
// parse_int(""); // Returns 0
function parse_int(str,base=10) =
str==undef ? undef :
len(str)==0 ? 0 :
len(str)==0 ? 0 :
let(str=downcase(str))
str[0] == "-" ? -_parse_int_recurse(substr(str,1),base,len(str)-2) :
str[0] == "+" ? _parse_int_recurse(substr(str,1),base,len(str)-2) :
@ -402,11 +447,14 @@ function _parse_int_recurse(str,base,i) =
let(
digit = search(str[i],"0123456789abcdef"),
last_digit = digit == [] || digit[0] >= base ? (0/0) : digit[0]
) i==0 ? last_digit :
) i==0 ? last_digit :
_parse_int_recurse(str,base,i-1)*base + last_digit;
// Function: parse_float()
// Synopsis: Parse a float from a string.
// Topics: Strings
// See Also: parse_int(), parse_float(), parse_frac(), parse_num()
// Usage:
// num = parse_float(str);
// Description:
@ -435,23 +483,26 @@ function parse_float(str) =
// Function: parse_frac()
// Synopsis: Parse a float from a fraction string.
// Topics: Strings
// See Also: parse_int(), parse_float(), parse_frac(), parse_num()
// Usage:
// num = parse_frac(str,[mixed=],[improper=],[signed=]);
// Description:
// Converts a string fraction to a floating point number. A string fraction has the form `[-][# ][#/#]` where each `#` is one or more of the
// digits 0-9, and there is an optional sign character at the beginning.
// digits 0-9, and there is an optional sign character at the beginning.
// The full form is a sign character and an integer, followed by exactly one space, followed by two more
// integers separated by a "/" character. The leading integer and
// integers separated by a "/" character. The leading integer and
// space can be omitted or the trailing fractional part can be omitted. If you set `mixed` to false then the leading integer part is not
// accepted and the input must include a slash. If you set `improper` to false then the fractional part must be a proper fraction, where
// the numerator is smaller than the denominator. If you set `signed` to false then the leading sign character is not permitted.
// The empty string evaluates to zero. Any invalid string evaluates to NaN.
// The empty string evaluates to zero. Any invalid string evaluates to NaN.
// Arguments:
// str = String to convert.
// ---
// mixed = set to true to accept mixed fractions, false to reject them. Default: true
// mixed = set to true to accept mixed fractions, false to reject them. Default: true
// improper = set to true to accept improper fractions, false to reject them. Default: true
// signed = set to true to accept a leading sign character, false to reject. Default: true
// signed = set to true to accept a leading sign character, false to reject. Default: true
// Example:
// parse_frac("3/4"); // Returns 0.75
// parse_frac("-77/9"); // Returns -8.55556
@ -473,7 +524,7 @@ function parse_frac(str,mixed=true,improper=true,signed=true) =
: str[0]==" " ? NAN
: signed && str[0]=="-" ? -parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false)
: signed && str[0]=="+" ? parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false)
: mixed && (str_find(str," ")!=undef || str_find(str,"/")==undef)? // Mixed allowed and there is a space or no slash
: mixed && (str_find(str," ")!=undef || str_find(str,"/")==undef)? // Mixed allowed and there is a space or no slash
let(whole = str_split(str,[" "]))
_parse_int_recurse(whole[0],10,len(whole[0])-1) + parse_frac(whole[1], mixed=false, improper=improper, signed=false)
: let(split = str_split(str,"/"))
@ -488,6 +539,9 @@ function parse_frac(str,mixed=true,improper=true,signed=true) =
// Function: parse_num()
// Synopsis: Parse a float from a decimal or fraction string.
// Topics: Strings
// See Also: parse_int(), parse_float(), parse_frac(), parse_num()
// Usage:
// num = parse_num(str);
// Description:
@ -508,6 +562,9 @@ function parse_num(str) =
// Section: Formatting numbers into strings
// Function: format_int()
// Synopsis: Formats an integer into a string, with possible leading zeros.
// Topics: Strings
// See Also: format_int(), format_fixed(), format_float(), format()
// Usage:
// str = format_int(i, [mindigits]);
// Description:
@ -532,6 +589,9 @@ function format_int(i,mindigits=1) =
// Function: format_fixed()
// Synopsis: Formats a float into a string with a fixed number of decimal places.
// Topics: Strings
// See Also: format_int(), format_fixed(), format_float(), format()
// Usage:
// s = format_fixed(f, [digits]);
// Description:
@ -556,6 +616,9 @@ function format_fixed(f,digits=6) =
// Function: format_float()
// Synopsis: Formats a float into a string with a given number of significant digits.
// Topics: Strings
// See Also: format_int(), format_fixed(), format_float(), format()
// Usage:
// str = format_float(f,[sig]);
// Description:
@ -607,13 +670,13 @@ function format_float(f,sig=12) =
/// Convert a numerical matrix into a matrix of strings where every column
/// is the same width so it will display in neat columns when printed.
/// Values below eps will display as zero. The matrix can include nans, infs
/// or undefs and the rows can be different lengths.
/// or undefs and the rows can be different lengths.
/// Arguments:
/// M = numerical matrix to convert
/// sig = significant digits to display. Default: 4
// sep = number of spaces between columns or a text string to separate columns. Default: 1
/// eps = values smaller than this are shown as zero. Default: 1e-9
function _format_matrix(M, sig=4, sep=1, eps=1e-9) =
function _format_matrix(M, sig=4, sep=1, eps=1e-9) =
let(
figure_dash = chr(8210),
space_punc = chr(8200),
@ -637,7 +700,7 @@ function _format_matrix(M, sig=4, sep=1, eps=1e-9) =
]
],
maxwidth = max([for(row=M) len(row)]),
// Find maximum length for each column. Some entries in a column may be missing.
// Find maximum length for each column. Some entries in a column may be missing.
maxlen = [for(i=[0:1:maxwidth-1])
max(
[for(j=idx(M)) i>=len(M[j]) ? 0 : len(strarr[j][i])])
@ -655,6 +718,9 @@ function _format_matrix(M, sig=4, sep=1, eps=1e-9) =
// Function: format()
// Synopsis: Formats multiple values into a string with a given format.
// Topics: Strings
// See Also: format_int(), format_fixed(), format_float(), format()
// Usage:
// s = format(fmt, vals);
// Description:
@ -737,12 +803,15 @@ function format(fmt, vals) =
out, raw
]
]);
// Section: Checking character class
// Function: is_lower()
// Synopsis: Returns true if all characters in the string are lowercase.
// Topics: Strings
// See Also: is_lower(), is_upper(), is_digit(), is_hexdigit(), is_letter()
// Usage:
// x = is_lower(s);
// Description:
@ -755,6 +824,9 @@ function is_lower(s) =
// Function: is_upper()
// Synopsis: Returns true if all characters in the string are uppercase.
// Topics: Strings
// See Also: is_lower(), is_upper(), is_digit(), is_hexdigit(), is_letter()
// Usage:
// x = is_upper(s);
// Description:
@ -767,6 +839,9 @@ function is_upper(s) =
// Function: is_digit()
// Synopsis: Returns true if all characters in the string are decimal digits.
// Topics: Strings
// See Also: is_lower(), is_upper(), is_digit(), is_hexdigit(), is_letter()
// Usage:
// x = is_digit(s);
// Description:
@ -779,6 +854,9 @@ function is_digit(s) =
// Function: is_hexdigit()
// Synopsis: Returns true if all characters in the string are hexidecimal digits.
// Topics: Strings
// See Also: is_lower(), is_upper(), is_digit(), is_hexdigit(), is_letter()
// Usage:
// x = is_hexdigit(s);
// Description:
@ -794,6 +872,9 @@ function is_hexdigit(s) =
// Function: is_letter()
// Synopsis: Returns true if all characters in the string are letters.
// Topics: Strings
// See Also: is_lower(), is_upper(), is_digit(), is_hexdigit(), is_letter()
// Usage:
// x = is_letter(s);
// Description: