8.0 String Variable Tips
[8.1] Convert integers to strings without extra characters
When building strings to evaluate with expr(), you may need to insert integer strings in the string. For
example, suppose you want to build the string "y{n}(x)", where {n} is an integer that is determined while
the program is running. This won't always work:
"y"&string(n)&"(x)"
If the current mode is Exact/Approx mode is Exact, this works as expected. However, if the mode is
Approx, and the user has set the Exponential Format mode to Engineering or Scientific, you'll get this:
string(1) results in "1.E0"
which causes problems if replaced in the example string above. Instead of using string(n), use
string(exact(n))
which will return just the integer, without decimal points, trailing zeroes, or the 'E' symbol, regardless of
the mode settings.
[8.2] String substitutions
Occasionally it is necessary to replace all occurrences of some substring within a string with a different
string. For example, if we replace all of the "c"s in "acbc" with "x", we get "axbx". This code
accomplishes this function:
strsub(s,so,sn)
func
©strsub(string,oldsub,newsub)
Local c,sl
""→sl
instring(s,so)→c
while c>0
sl&mid(s,1,c-1)&sn→sl
mid(s,c+dim(so))→s
instring(s,so)→c
endwhile
return sl&s
endfunc
where s is the target string, so is the original pattern to be replaced, and sn is the replacement. So to
use this program with my example, we would call it like this:
strsub("acbc","c","x").
(credit declined)
8 - 1