2 summary::array of characters
3 categories:: Collections>Ordered
6 String represents an array of characters.
8 Strings can be written literally using double quotes:
12 A sequence of string literals will be concatenated together:
23 private::doUnixCmdAction
24 private::unixCmdActions
27 Read the entire contents of a link::Classes/File:: and return them as a new String.
30 Provided for backwards compatibility.
32 the value of code::Platform.resourceDir::, which is the base resource directory of SuperCollider.
34 Please use link::Classes/Platform#*resourceDir:: instead.
38 private::prUnixCmd, prFormat, prCat, prBounds, hash, species, getSCDir, prDrawInRect, prDrawAtPoint, openTextFile
40 subsection:: Accessing characters
43 Strings respond to .at in a manner similar to other indexed collections. Each element is a link::Classes/Char::.
49 Returns an Array of asci numbers of the Strings's characters.
54 subsection:: Comparing strings
57 Returns a -1, 0, or 1 depending on whether the receiver should be sorted before the argument, is equal to the argument or should be sorted after the argument. This is a case sensitive compare.
60 Returns a link::Classes/Boolean:: whether the receiver should be sorted before the argument.
66 Returns a link::Classes/Boolean:: whether the receiver should be sorted after the argument.
71 Returns a link::Classes/Boolean:: whether the receiver should be sorted before the argument, including the same string.
78 Returns a link::Classes/Boolean:: whether the receiver should be sorted after the argument, including the same string.
85 Returns a link::Classes/Boolean:: whether the two Strings are equal.
87 This method is (now) case sensitive!
91 "same" == "Same"; // false
95 Returns a link::Classes/Boolean:: whether the two Strings are not equal.
97 "same" != "same"; // false
101 subsection:: Posting strings
104 Prints the string to the current post window.
106 "One".post; "Two".post;"";
110 Prints the string and a carriage return to the current post window.
112 "One".postln; "Two".postln;"";
115 method::postc, postcln
116 As link::#-post:: and link::#-postln::, but formatted as a comment.
118 "This is a comment.".postcln;
122 Prints a formatted string with arguments to the current post window. The % character in the format string is replaced by a string representation of an argument. To print a % character use \\% .
124 postf("this % a %. pi = %, list = %\n", "is", "test", pi.round(1e-4), (1..4))
126 this is a test. pi = 3.1416, list = [ 1, 2, 3, 4 ]
130 As link::#-postln::, but posts the link::#-asCompileString#compileString:: of the reciever.
132 List[1, 2, ["comment", [3, 2]], { 1.0.rand }].postcs;
136 Prepends an error banner and posts the string.
138 "Do not press this button again".error;
142 Prepends a warning banner and posts the string.
144 "Do not press this button again".warn;
150 "Do not press this button again".inform;
153 subsection:: Interpreting strings as code
156 Compiles a String containing legal SuperCollider code and returns a Function.
160 f = "2 + 1".compile.postln;
166 Compile and execute a String containing legal SuperCollider code, returning the result.
168 "2 + 1".interpret.postln;
171 method::interpretPrint
172 Compile, execute and print the result of a String containing legal SuperCollider code.
174 "2 + 1".interpretPrint;
177 subsection:: Converting strings
179 method::asCompileString
180 Returns a String formatted for compiling.
186 f.asCompileString.postln;
191 Return a link::Classes/Symbol:: derived from the String.
195 z = "myString".asSymbol.postln;
201 Return an link::Classes/Integer:: derived from the String. Strings beginning with non-numeric characters return 0.
203 "4".asInteger.postln;
207 Return a link::Classes/Float:: derived from the String. Strings beginning with non-numeric characters return 0.
209 "4.3".asFloat.postln;
213 Return a link::Classes/Float:: based on converting a time string in format (dd):hh:mm:ss.s. This is the inverse method to link::Classes/SimpleNumber#-asTimeString::.
215 (45296.asTimeString).asSecs;
217 "62.1".asSecs; // warns
220 "-1".asSecs; // neg sign supported
222 "12:-34:56".asSecs; // warns
223 "-23:12.3456".asSecs; //
224 "-1:00:00:00".asSecs; // days too.
227 subsection:: Concatenate strings
230 Return a concatenation of the two strings.
236 Return a concatenation of the two strings with a space between them.
242 Path concatenation operator - useful for avoiding doubling-up slashes unnecessarily.
243 code::"foo"+/+"bar":: returns code::"foo/bar"::
246 Concatenate this string with the following args.
248 "These are some args: ".catArgs(\fish, SinOsc.ar, {4 + 3}).postln;
252 Same as link::#-catArgs::, but with spaces in between.
254 "These are some args: ".scatArgs(\fish, SinOsc.ar, {4 + 3}).postln;
258 Same as link::#-catArgs::, but with commas in between.
260 "a String".ccatArgs(\fish, SinOsc.ar, {4 + 3}).postln;
263 method::catList, scatList, ccatList
264 As link::#-catArgs::, link::#-scatArgs:: and link::#-ccatArgs:: above, but takes a Collection (usually a link::Classes/List:: or an link::Classes/Array::) as an argument.
266 "a String".ccatList([\fish, SinOsc.ar, {4 + 3}]).postln;
271 subsection:: Regular expressions
274 POSIX regular expression matching. Returns true if the receiver (a regular expression pattern) matches the string passed to it. The strong::start:: is an offset where to start searching in the string (default: 0), strong::end:: where to stop.
276 "c".matchRegexp("abcdefg", 2, 5); // true
277 "c".matchRegexp("abcdefg", 4, 5); // false
279 "behaviou?r".matchRegexp("behavior"); // true
280 "behaviou?r".matchRegexp("behaviour"); // true
281 "behaviou?r".matchRegexp("behavir"); // false
282 "b.h.v.r".matchRegexp("behavor"); // true
283 "b.h.vi*r".matchRegexp("behaviiiiir"); // true
284 "(a|u)nd".matchRegexp("und"); // true
285 "(a|u)nd".matchRegexp("and"); // true
286 "[a-c]nd".matchRegexp("ind"); // false
287 "[a-c]nd".matchRegexp("bnd"); // true
291 POSIX regular expression search.
293 "foobar".findRegexp("o*bar");
294 "32424 334 /**aaaaaa*/".findRegexp("/\\*\\*a*\\*/");
295 "foobar".findRegexp("(o*)(bar)");
296 "aaaabaaa".findAllRegexp("a+");
299 method::findAllRegexp
300 Like link::#-findAll::, but use regular expressions.
302 subsection:: Searching strings
305 Returns the index of the string in the receiver, or nil if not found. If strong::ignoreCase:: is true, find makes no difference between uppercase and lowercase letters. The strong::offset:: is the point in the string where the search begins.
307 "These are several words".find("are").postln;
308 "These are several words".find("fish").postln;
311 method::findBackwards
312 Same like link::#-find::, but starts at the end of the string.
315 "These words are several words".find("words"); // 6
316 "These words are several words".findBackwards("words"); // 24
320 Returns the indices of the string in the receiver, or nil if not found.
322 "These are several words which are fish".findAll("are").postln;
323 "These are several words which are fish".findAll("fish").postln;
327 Returns a link::Classes/Boolean:: indicating if the String contains string.
329 "These are several words".contains("are").postln;
330 "These are several words".contains("fish").postln;
334 Same as link::#-contains::, but case insensitive.
336 "These are several words".containsi("ArE").postln;
339 method::containsStringAt
340 Returns a link::Classes/Boolean:: indicating if the String contains string beginning at the specified index.
342 "These are several words".containsStringAt(6, "are").postln;
345 method::icontainsStringAt
346 Same as link::#-containsStringAt::, but case insensitive.
350 Returns true if this string begins/ends with the specified other string.
354 A link::Classes/Boolean::
356 subsection:: Manipulating strings
359 Rotate the string by n steps.
361 "hello word".rotate(1)
365 Randomize the order of characters in the string.
367 "hello word".scramble
372 Like link::#-tr::, but with strings as arguments.
374 "Here are several words which are fish".replace("are", "were");
378 Returns a formatted string with arguments. The % character in the format string is replaced by a string representation of an argument. To print a % character use \\% .
380 format("this % a %. pi = %, list = %\n", "is", "test", pi.round(1e-4), (1..4))
382 this is a test. pi = 3.1416, list = [ 1, 2, 3, 4 ]
386 Add the escape character (\) before any character of your choice.
389 "This will become a Unix friendly string".escapeChar($ ).postln;
393 Return this string enclosed in double-quote ( teletype::":: ) characters.
395 "tell your" + "friends".quote + "not to tread onto the lawn"
399 Return this string enclosed in space characters.
401 "spaces".zeroPad.postcs;
405 Return this string followed by dashes in the next line ( teletype::-:: ).
407 "underlined".underlined;
408 "underlined".underlined($~);
412 Transliteration. Replace all instances of strong::from:: with strong::to::.
414 ":-(:-(:-(".tr($(, $)); //turn the frowns upside down
420 Pad this string with strong::string:: so it fills strong::size:: character.
422 Number of characters to fill
426 "this sentence has thirty-nine letters".padRight(39, "-+");
427 "this sentence has thirty-nine letters".padLeft(39, "-+");
428 "this sentence more than thirteen letters".padRight(13, "-+"); // nothing to pad.
432 Return this string with uppercase letters.
434 "Please, don't be impolite".toUpper;
438 Return this string with lowercase letters.
444 Returns a new String with all RTF formatting removed.
447 // same as File-readAllStringRTF
448 g = File("/code/SuperCollider3/build/Help/UGens/Chaos/HenonC.help.rtf","r");
449 g.readAllString.stripRTF.postln;
455 Returns an Array of Strings split at the separator. The separator is a link::Classes/Char::, a link::Classes/String::, or anything that can be converted into a string. It is strong::not:: included in the output array. The default separator is $/, handy for Unix paths.
457 "This/could/be/a/Unix/path".split;
458 "These are several words".split($ );
459 "These are several words".split(" ");
460 "accgcagcttag".split("gc");
463 subsection:: Stream support
466 Print the String on stream.
468 "Print this on Post".printOn(Post);
471 Post << "Print this on Post";
475 Same as link::#-printOn::, but formatted link::#-asCompileString::.
477 "Store this on Post".storeOn(Post);
480 Post <<< "Store this on Post";
485 subsection::Unix Support
487 Where relevant, the current working directory is the same as the location of the SuperCollider app and the shell is the Bourne shell (sh). Note that the cwd, and indeed the shell itself, does not persist:
489 "echo $0".unixCmd; // print the shell (sh)
494 "export FISH=mackerel".unixCmd;
495 "echo $FISH".unixCmd;
497 It is however possible to execute complex commands:
499 "pwd; cd Help/; pwd".unixCmd;
500 "export FISH=mackerel; echo $FISH".unixCmd;
502 Also on os x applescript can be called via osascript:
504 "osascript -e 'tell application \"Safari\" to activate'".unixCmd;
506 Should you need an environment variable to persist you can use link::#-setenv::.
509 Despite the fact that the method is called 'unixCmd', strong::it does work in Windows::. The string must be a DOS command, however: "dir" rather than "ls" for instance.
513 Execute a unix command asynchronously using the standard shell (sh).
515 A link::Classes/Function:: that is called when the process has exited. It is passed two arguments: the exit code and pid of the exited process.
516 argument:: postOutput
517 A link::Classes/Boolean:: that controls whether or not the output of the process is displayed in the post window.
519 An link::Classes/Integer:: - the pid of the newly created process. Use link::Classes/Integer#-pidRunning:: to test if a process is alive.
524 "echo one; sleep 1; echo two; sleep 1".unixCmd { |res, pid| [\done, res, pid].postln };
527 method::unixCmdGetStdOut
528 Similar to link::#-unixCmd:: except that the stdout of the process is returned (synchronously) rather than sent to the post window.
530 ~listing = "ls Help".unixCmdGetStdOut; // Grab
531 ~listing.reverse.as(Array).stutter.join.postln; // Mangle
535 Executes a unix command synchronously using the standard shell (sh).
537 returns:: Error code of the unix command
539 method::runInTerminal
540 Execute the String in a new terminal window (asynchronously).
542 The shell used to execute the string.
544 note:: On OSX, the string is incorporated into a temporary script file and executed using the shell. ::
547 "echo ---------Hello delightful SuperCollider user----------".runInTerminal;
551 Set the environment variable indicated in the string to equal the String strong::value::. This value will persist until it is changed or SC is quit. Note that if strong::value:: is a path you may need to call link::#-standardizePath:: on it.
553 // all defs in this directory will be loaded when a local server boots
554 "SC_SYNTHDEF_PATH".setenv("~/scwork/".standardizePath);
555 "echo $SC_SYNTHDEF_PATH".unixCmd;
559 Returns the value contained in the environment variable indicated by the String.
565 Set the environment variable to nil.
568 Make a directory from the given path location.
571 Returns an link::Classes/Array:: containing all paths matching this String. Wildcards apply, non-recursive.
573 Post << "Help/*".pathMatch;
577 Perform link::#-pathMatch:: on this String, then load and execute all paths in the resultant link::Classes/Array::.
579 //first prepare a file with some code...
581 var f = File("/tmp/loadPaths_example.scd", "w");
583 f.putString("\"This text is the result of a postln command which was loaded and executed by loadPaths\".postln");
585 "test file could not be created - please edit the file's path above".warn;
590 //then load the file...
591 "/tmp/loadPaths_example.scd".loadPaths; //This file posts some text
595 Load and execute the file at the path represented by the receiver.
598 Load and execute the file at the path represented by the receiver, interpreting the path as relative to the current document or text file. Requires that the file has been saved.
600 method::resolveRelative
601 Convert the receiver from a relative path to an absolute path, relative to the current document or text file. Requires that the current text file has been saved. Absolute paths are left untransformed.
603 method::standardizePath
604 Expand ~ to your home directory, and resolve aliases on OSX. See link::Classes/PathName:: for more complex needs. See link::Classes/File#*realpath:: if you want to resolve symlinks.
606 "~/".standardizePath; //This will print your home directory
611 Open file, directory or URL via the operating system. On OSX this is implemented via teletype::open::, on Linux via
612 teletype::xdg-open:: and on Windows via teletype::start::.
614 Platform.userConfigDir.openOS;
615 "http://supercollider.sf.net".openOS;
618 subsection::Pathname Support
620 Also see link::#-+/+:: for path concatenation.
623 Return a new string suitable for use as a filename in a shell command, by enclosing it in single quotes ( teletype::':: ).
624 If the string contains any single quotes they will be escaped.
626 You should use this method on a path before embedding it in a string executed by link::#-unixCmd:: or link::#-systemCmd::.
628 unixCmd("ls " + Platform.userExtensionDir.shellQuote)
631 This works well with shells such as strong::bash::, other shells might need different quotation/escaping.
632 Apart from usage in the construction of shell commands, strong::escaping is not needed:: for paths passed to methods like pathMatch(path) or File.open(path).
636 method::asAbsolutePath
637 Return this path as an absolute path by prefixing it with link::Classes/File#*getcwd:: if necessary.
639 method::asRelativePath
640 Return this path as relative to the specified path.
642 The path to make this path relative to.
644 method::withTrailingSlash
645 Return this string with a trailing slash if that was not already the case.
647 method::withoutTrailingSlash
648 Return this string without a trailing slash if that was not already the case.
651 Return the filename from a Unix path.
653 "Imaginary/Directory/fish.rtf".basename;
657 Return the directory name from a Unix path.
659 "Imaginary/Directory/fish.rtf".dirname;
663 Split off the extension from a filename or path and return both in an link::Classes/Array:: as [path or filename, extension].
666 "Imaginary/Directory/fish.rtf".splitext;
669 subsection::YAML and JSON parsing
672 Parse this string as YAML/JSON.
674 A nested structure of link::Classes/Array::s (for sequences), link::Classes/Dictionary##Dictionaries:: (for maps) and link::Classes/String::s (for scalars).
676 method::parseYAMLFile
677 Same as code::parseYAML:: but parse a file directly instead of a string. This is faster than reading a file into a string and then parse it.
679 subsection::Document Support
681 method::newTextWindow
682 Create a new link::Classes/Document:: with this.
684 "Here is a new Document".newTextWindow;
688 Create a new link::Classes/Document:: from the path corresponding to this. The selection arguments will preselect the indicated range in the new window. Returns this.
691 String.filenameSymbol.asString.openDocument(10, 20)
696 Returns the path for the helpfile named this, if it exists, else returns nil.
698 "Document".findHelpFile;
699 "foobar".findHelpFile;
703 Performs link::#-findHelpFile:: on this, and opens the file it if it exists, otherwise opens the main helpfile.
709 subsection::Misc methods
712 Sends string to the speech synthesisier of the OS. (OS X only.) see: link::Classes/Speech::
714 "hi i'm talking with the default voice now, i guess".speak;
717 method::inspectorClass
718 Returns class link::Classes/StringInspector::.
721 subsection::Drawing Support
723 The following methods must be called within an Window-drawFunc or a SCUserView-drawFunc function, and will only be visible once the window or the view is refreshed. Each call to Window-refresh SCUserView-refresh will 'overwrite' all previous drawing by executing the currently defined function.
725 See also: link::Classes/Window::, link::Classes/UserView::, link::Classes/Color::, and link::Classes/Pen::.
728 for cross-platform GUIs, use code::Pen.stringAtPoint, Pen.stringInRect, Pen.stringCenteredIn, Pen.stringLeftJustIn, Pen.stringRightJustIn:: instead.
732 Draws the String at the current 0@0 link::Classes/Point::. If not transformations of the graphics state have taken place this will be the upper left corner of the window. See also link::Classes/Pen::.
735 w = Window.new.front;
736 w.view.background_(Color.white);
738 "abababababa\n\n\n".scramble.draw
745 Draws the String at the given link::Classes/Point:: using the link::Classes/Font:: and link::Classes/Color:: specified.
748 w = Window.new.front;
749 w.view.background_(Color.white);
751 "abababababa\n\n\n".scramble.drawAtPoint(
754 Color.blue(0.3, 0.5))
761 Draws the String into the given link::Classes/Rect:: using the link::Classes/Font:: and link::Classes/Color:: specified.
764 w = Window.new.front;
765 r = Rect(100, 100, 100, 100);
766 w.view.background_(Color.white);
768 "abababababa\n\n\n".scramble.drawInRect(r, Font("Courier", 12), Color.blue(0.3, 0.5));
775 method::drawCenteredIn
776 Draws the String into the given Rect using the Font and Color specified.
779 w = Window.new.front;
780 w.view.background_(Color.white);
781 r = Rect(100, 100, 100, 100);
783 "abababababa\n\n\n".scramble.drawCenteredIn(
794 method::drawLeftJustIn
795 Draws the String into the given Rect using the Font and Color specified.
798 w = Window.new.front;
799 w.view.background_(Color.white);
800 r = Rect(100, 100, 100, 100);
802 "abababababa\n\n\n".scramble.drawLeftJustIn(
813 method::drawRightJustIn
814 Draws the String into the given link::Classes/Rect:: using the link::Classes/Font:: and link::Classes/Color:: specified.
817 w = Window.new.front;
818 w.view.background_(Color.white);
819 r = Rect(100, 100, 100, 100);
821 "abababababa\n\n\n".scramble.drawRightJustIn(
833 Tries to return a link::Classes/Rect:: with the size needed to fit this string if drawed with given font.
835 A link::Classes/Font::