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:
10 "my string".class.postln;
16 private::doUnixCmdAction
17 private::unixCmdActions
20 Read the entire contents of a link::Classes/File:: and return them as a new String.
23 Return the base resource directory of SuperCollider.
27 private::prUnixCmd, prFormat, prCat, prBounds, hash, species, getSCDir, prDrawInRect, prDrawAtPoint
29 subsection:: Accessing characters
33 Strings respond to .at in a manner similar to other indexed collections. Each element is a link::Classes/Char::.
35 "ABCDEFG".at(2).postln;
39 Returns an Array of asci numbers of the Strings's characters.
44 subsection:: Comparing strings
47 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.
50 Returns a link::Classes/Boolean:: whether the receiver should be sorted before the argument.
53 Returns a link::Classes/Boolean:: whether the receiver should be sorted after the argument.
56 Returns a link::Classes/Boolean:: whether the two Strings are equal.
59 Returns a link::Classes/Boolean:: whether the two Strings are not equal.
61 subsection:: Posting strings
64 Prints the string to the current post window.
67 Prints the string and a carriage return to the current post window.
69 method::postc, postcln
70 As link::#-post:: and link::#-postln::, but formatted as a comment.
72 "This is a comment.".postcln;
76 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 \\% .
78 postf("this % a %. pi = %, list = %\n", "is", "test", pi.round(1e-4), (1..4))
80 this is a test. pi = 3.1416, list = [ 1, 2, 3, 4 ]
84 As link::#-postln::, but posts the link::#-asCompileString#compileString:: of the reciever.
86 List[1, 2, ["comment", [3, 2]], { 1.0.rand }].postcs;
90 Prepends an error banner and posts the string.
94 Prepends a warning banner and posts the string.
99 subsection:: Interpreting strings as code
102 Compiles a String containing legal SuperCollider code and returns a Function.
106 f = "2 + 1".compile.postln;
112 Compile and execute a String containing legal SuperCollider code, returning the result.
114 "2 + 1".interpret.postln;
117 method::interpretPrint
118 Compile, execute and print the result of a String containing legal SuperCollider code.
120 "2 + 1".interpretPrint;
123 subsection:: Converting strings
125 method::asCompileString
126 Returns a String formatted for compiling.
132 f.asCompileString.postln;
137 Return a link::Classes/Symbol:: derived from the String.
141 z = "myString".asSymbol.postln;
147 Return an link::Classes/Integer:: derived from the String. Strings beginning with non-numeric characters return 0.
149 "4".asInteger.postln;
153 Return a link::Classes/Float:: derived from the String. Strings beginning with non-numeric characters return 0.
155 "4.3".asFloat.postln;
159 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::.
161 (45296.asTimeString).asSecs;
163 "62.1".asSecs; // warns
166 "-1".asSecs; // neg sign supported
168 "12:-34:56".asSecs; // warns
169 "-23:12.3456".asSecs; //
170 "-1:00:00:00".asSecs; // days too.
173 subsection:: Concatenate strings
176 Return a concatenation of the two strings.
180 Return a concatenation of the two strings with a space between them.
183 Path concatenation operator - useful for avoiding doubling-up slashes unnecessarily.
184 code::"foo"+/+"bar":: returns code::"foo/bar"::
187 Concatenate this string with the following args.
189 "These are some args: ".catArgs(\fish, SinOsc.ar, {4 + 3}).postln;
193 Same as link::#-catArgs::, but with spaces in between.
195 "These are some args: ".scatArgs(\fish, SinOsc.ar, {4 + 3}).postln;
199 Same as link::#-catArgs::, but with commas in between.
201 "a String".ccatArgs(\fish, SinOsc.ar, {4 + 3}).postln;
204 method::catList, scatList, ccatList
205 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.
207 "a String".ccatList([\fish, SinOsc.ar, {4 + 3}]).postln;
212 subsection:: Regular expressions
215 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.
217 "c".matchRegexp("abcdefg", 2, 5); // true
218 "c".matchRegexp("abcdefg", 4, 5); // false
220 "behaviou?r".matchRegexp("behavior"); // true
221 "behaviou?r".matchRegexp("behaviour"); // true
222 "behaviou?r".matchRegexp("behavir"); // false
223 "b.h.v.r".matchRegexp("behavor"); // true
224 "b.h.vi*r".matchRegexp("behaviiiiir"); // true
225 "(a|u)nd".matchRegexp("und"); // true
226 "(a|u)nd".matchRegexp("and"); // true
227 "[a-c]nd".matchRegexp("ind"); // false
228 "[a-c]nd".matchRegexp("bnd"); // true
232 POSIX regular expression search.
234 "foobar".findRegexp("o*bar");
235 "32424 334 /**aaaaaa*/".findRegexp("/\\*\\*a*\\*/");
236 "foobar".findRegexp("(o*)(bar)");
237 "aaaabaaa".findAllRegexp("a+");
241 subsection:: Searching strings
244 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.
246 "These are several words".find("are").postln;
247 "These are several words".find("fish").postln;
250 method::findBackwards
251 Same like link::#-find::, but starts at the end of the string.
254 "These words are several words".find("words"); // 6
255 "These words are several words".findBackwards("words"); // 24
259 Returns the indices of the string in the receiver, or nil if not found.
261 "These are several words which are fish".findAll("are").postln;
262 "These are several words which are fish".findAll("fish").postln;
266 Returns a link::Classes/Boolean:: indicating if the String contains string.
268 "These are several words".contains("are").postln;
269 "These are several words".contains("fish").postln;
273 Same as link::#-contains::, but case insensitive.
275 "These are several words".containsi("ArE").postln;
278 method::containsStringAt
279 Returns a link::Classes/Boolean:: indicating if the String contains string beginning at the specified index.
281 "These are several words".containsStringAt(6, "are").postln;
284 method::icontainsStringAt
285 Same as link::#-containsStringAt::, but case insensitive.
289 Returns true if this string begins/ends with the specified other string.
293 A link::Classes/Boolean::
295 subsection:: Manipulating strings
298 Add the escape character (\) before any character of your choice.
301 "This will become a Unix friendly string".escapeChar($ ).postln;
305 Return a new string suitable for use as a filename in a shell command, by enclosing it in single quotes ( teletype::':: ).
306 If the string contains any single quotes they will be escaped.
308 You should use this method on a path before embedding it in a string executed by link::#-unixCmd:: or link::#-systemCmd::.
310 unixCmd("ls"+Platform.userExtensionDir.shellQuote)
313 This works well with shells such as strong::bash::, other shells might need different quotation/escaping.
317 Return this string enclosed in double-quote ( teletype::":: ) characters.
320 Transliteration. Replace all instances of strong::from:: with strong::to::.
322 ":-(:-(:-(".tr($(, $)); //turn the frowns upside down
326 Like link::#-tr::, but with strings as arguments.
328 "Here are several words which are fish".replace("are", "were");
332 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 \\% .
334 format("this % a %. pi = %, list = %\n", "is", "test", pi.round(1e-4), (1..4))
336 this is a test. pi = 3.1416, list = [ 1, 2, 3, 4 ]
342 Pad this string with strong::string:: so it fills strong::size:: character.
344 Number of characters to fill
349 Return this string with uppercase letters.
352 Return this string with lowercase letters.
355 Returns a new String with all RTF formatting removed.
358 // same as File-readAllStringRTF
359 g = File("/code/SuperCollider3/build/Help/UGens/Chaos/HenonC.help.rtf","r");
360 g.readAllString.stripRTF.postln;
366 Returns an Array of Strings split at the separator. The separator is a link::Classes/Char::, and is not included in the output array. The default separator is $/, handy for Unix paths.
368 "This/could/be/a/Unix/path".split.postln;
369 "These are several words".split($ ).postln;
372 subsection:: Stream support
375 Print the String on stream.
377 "Print this on Post".printOn(Post);
380 Post << "Print this on Post";
384 Same as link::#-printOn::, but formatted link::#-asCompileString::.
386 "Store this on Post".storeOn(Post);
389 Post <<< "Store this on Post";
394 subsection::Unix Support
396 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:
398 "echo $0".unixCmd; // print the shell (sh)
403 "export FISH=mackerel".unixCmd;
404 "echo $FISH".unixCmd;
406 It is however possible to execute complex commands:
408 "pwd; cd Help/; pwd".unixCmd;
409 "export FISH=mackerel; echo $FISH".unixCmd;
411 Also on os x applescript can be called via osascript:
413 "osascript -e 'tell application \"Safari\" to activate'".unixCmd;
415 Should you need an environment variable to persist you can use link::#-setenv::.
418 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.
422 Execute a unix command asynchronously using the standard shell (sh).
424 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.
425 argument:: postOutput
426 A link::Classes/Boolean:: that controls whether or not the output of the process is displayed in the post window.
428 An link::Classes/Integer:: - the pid of the newly created process. Use link::Classes/Integer#-pidRunning:: to test if a process is alive.
433 "echo one; sleep 1; echo two; sleep 1".unixCmd { |res, pid| [\done, res, pid].postln };
436 method::unixCmdGetStdOut
437 Similar to link::#-unixCmd:: except that the stdout of the process is returned (synchronously) rather than sent to the post window.
439 ~listing = "ls Help".unixCmdGetStdOut; // Grab
440 ~listing.reverse.as(Array).stutter.join.postln; // Mangle
444 Executes a unix command synchronously using the standard shell (sh).
446 returns:: Error code of the unix command
448 method::runInTerminal
449 Execute the String in a new terminal window (asynchronously).
451 The shell used to execute the string.
453 note:: On OSX, the string is incorporated into a temporary script file and executed using the shell. ::
456 "echo ---------Hello delightful SuperCollider user----------".runInTerminal;
460 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.
462 // all defs in this directory will be loaded when a local server boots
463 "SC_SYNTHDEF_PATH".setenv("~/scwork/".standardizePath);
464 "echo $SC_SYNTHDEF_PATH".unixCmd;
468 Returns the value contained in the environment variable indicated by the String.
474 Returns an link::Classes/Array:: containing all paths matching this String. Wildcards apply, non-recursive.
476 Post << "Help/*".pathMatch;
480 Perform link::#-pathMatch:: on this String, then load and execute all paths in the resultant link::Classes/Array::.
482 //first prepare a file with some code...
484 var f = File("/tmp/loadPaths_example.scd", "w");
486 f.putString("\"This text is the result of a postln command which was loaded and executed by loadPaths\".postln");
488 "test file could not be created - please edit the file's path above".warn;
493 //then load the file...
494 "/tmp/loadPaths_example.scd".loadPaths; //This file posts some text
498 Load and execute the file at the path represented by the receiver.
502 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.
504 method::resolveRelative
505 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.
507 method::standardizePath
508 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.
510 "~/".standardizePath; //This will print your home directory
515 Open file, directory or URL via the operating system. On OSX this is implemented via teletype::open::, on Linux via
516 teletype::xdg-open:: and on Windows via teletype::start::.
518 Platform.userConfigDir.openOS;
519 "http://supercollider.sf.net".openOS;
522 subsection::Pathname Support
524 Also see link::#-+/+:: for path concatenation.
527 method::asAbsolutePath
528 Return this path as an absolute path by prefixing it with link::Classes/File#*getcwd:: if necessary.
530 method::asRelativePath
531 Return this path as relative to the specified path.
533 The path to make this path relative to.
535 method::withTrailingSlash
536 Return this string with a trailing slash if that was not already the case.
538 method::withoutTrailingSlash
539 Return this string without a trailing slash if that was not already the case.
542 Return the filename from a Unix path.
544 "Imaginary/Directory/fish.rtf".basename;
548 Return the directory name from a Unix path.
550 "Imaginary/Directory/fish.rtf".dirname;
554 Split off the extension from a filename or path and return both in an link::Classes/Array:: as [path or filename, extension].
557 "Imaginary/Directory/fish.rtf".splitext;
560 subsection::Document Support
562 method::newTextWindow
563 Create a new link::Classes/Document:: with this.
565 "Here is a new Document".newTextWindow;
569 Create a new link::Classes/Document:: from the path corresponding to this. Returns the Document.
572 d = "Help/Help.html".openDocument;
578 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.
581 d = "Help/Help.html".openTextFile(20, 210);
587 Returns the path for the helpfile named this, if it exists, else returns nil.
589 "Document".findHelpFile;
590 "foobar".findHelpFile;
594 Performs link::#-findHelpFile:: on this, and opens the file it if it exists, otherwise opens the main helpfile.
596 "Document".openHelpFile;
597 "foobar".openHelpFile;
600 subsection::Misc methods
603 Sends string to the speech synthesisier of the OS. (OS X only.) see: link::Classes/Speech::
605 "hi i'm talking with the default voice now, i guess".speak;
608 method::inspectorClass
609 Returns class link::Classes/StringInspector::.
612 subsection::Drawing Support
614 The following methods must be called within an Window-drawHook 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.
616 See also: link::Classes/Window::, link::Classes/UserView::, link::Classes/Color::, and link::Classes/Pen::.
619 for cross-platform GUIs, use code::Pen.stringAtPoint, Pen.stringInRect, Pen.stringCenteredIn, Pen.stringLeftJustIn, Pen.stringRightJustIn:: instead.
623 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::.
626 w = Window.new.front;
627 w.view.background_(Color.white);
629 "abababababa\n\n\n".scramble.draw
636 Draws the String at the given link::Classes/Point:: using the link::Classes/Font:: and link::Classes/Color:: specified.
639 w = Window.new.front;
640 w.view.background_(Color.white);
642 "abababababa\n\n\n".scramble.drawAtPoint(
645 Color.blue(0.3, 0.5))
652 Draws the String into the given link::Classes/Rect:: using the link::Classes/Font:: and link::Classes/Color:: specified.
655 w = Window.new.front;
656 r = Rect(100, 100, 100, 100);
657 w.view.background_(Color.white);
659 "abababababa\n\n\n".scramble.drawInRect(r, Font("Courier", 12), Color.blue(0.3, 0.5));
666 method::drawCenteredIn
667 Draws the String into the given Rect using the Font and Color specified.
670 w = Window.new.front;
671 w.view.background_(Color.white);
672 r = Rect(100, 100, 100, 100);
674 "abababababa\n\n\n".scramble.drawCenteredIn(
685 method::drawLeftJustIn
686 Draws the String into the given Rect using the Font and Color specified.
689 w = Window.new.front;
690 w.view.background_(Color.white);
691 r = Rect(100, 100, 100, 100);
693 "abababababa\n\n\n".scramble.drawLeftJustIn(
704 method::drawRightJustIn
705 Draws the String into the given link::Classes/Rect:: using the link::Classes/Font:: and link::Classes/Color:: specified.
708 w = Window.new.front;
709 w.view.background_(Color.white);
710 r = Rect(100, 100, 100, 100);
712 "abababababa\n\n\n".scramble.drawRightJustIn(
724 Tries to return a link::Classes/Rect:: with the size needed to fit this string if drawed with given font.
726 A link::Classes/Font::