String:
Filter:
Classes | Collections > Ordered

String : RawArray : ArrayedCollection : SequenceableCollection : Collection : Object

array of Chars
Source: String.sc

Description

String represents an array of Chars.

Strings can be written literally using double quotes:

A sequence of string literals will be concatenated together:

Backslash is the escape character. See Literals: Characters.

Character encodings

Note that, while Char does not support encodings aside from ASCIIโ€”such as multi-byte encodings like UTF-8 and UTF-16, or the full Latin-1 (ISO 8859-1) character setโ€”Chars with negative values are perfectly legal, and may be strung together in strings that use these encodings.

The SuperCollider IDE uses UTF-8 (a superset of ASCII) to decode and display strings, which means that the string "๐ŸŽน๐Ÿ™„๐ŸŽป๐Ÿ˜‚๐ŸŽš๏ธ๐ŸŽ›๏ธ๐ŸŽค๐Ÿ˜" can be written in the editor, posted in the post window, and treated for the most part like any other string. However, because non-ASCII UTF-8 characters consist of two or more bytes, and a SuperCollider String's members are one-bit Chars, concepts of size and indexing may not behave intuitively. For instance, the "size" of the string above is 38, not 8, and the value of its first index is -16, which is not a valid ASCII value at all but rather the signed 8-bit representation of the first byte of the UTF-8 value of the piano keyboard emoji (๐ŸŽน), 0xF09F8EB9.

Class Methods

String.readNew(file)

Read the entire contents of a File and return them as a new String.

String.scDir

From extension in /usr/local/share/SuperCollider/SCClassLibrary/deprecated/3.11/deprecated-3.11.sc

Deprecated alias for Platform.resourceDir. Please use Platform: *resourceDir instead.

Inherited class methods

Instance Methods

Accessing characters

@(index)

From superclass: Collection

.at(index)

From superclass: ArrayedCollection

Strings respond to .at in a manner similar to other indexed collections. Each element is a Char.

.ascii

Returns an Array of ASCII values of the Strings's characters.

Note that if a string contains multi-byte UTF-8 characters, this array will not be of the same length as the number of visible characters, nor will it necessarily be an array of valid 7-bit ASCII values.

Comparing strings

.compare(aString, ignoreCase: false)

Returns an integer less than, equal to or greater than zero, 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.

<(aString)

Returns a Boolean whether the receiver should be sorted before the argument.

>(aString)

Returns a Boolean whether the receiver should be sorted after the argument.

<=(aString)

Returns a Boolean whether the receiver should be sorted before the argument, including the same string.

>=(aString)

Returns a Boolean whether the receiver should be sorted after the argument, including the same string.

==(aString)

Returns a Boolean whether the two Strings are equal.

NOTE: This method is (now) case sensitive!

!=(aString)

Returns a Boolean whether the two Strings are not equal.

Fuzzy string comparison

With fuzzy comparison, the strings don't need to match exactly - we can work out how similar they are, and make decisions based on that. This behaviour is inherited from the SequenceableCollection: -editDistance, and is documented fully there, but to provide an example:

Posting strings

.post

Prints the string to the current post window.

.postln

Prints the string and a carriage return to the current post window.

.postc

.postcln

As -post and -postln, but formatted as a comment.

.postf( ... items)

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 \\% .

.postcs

From superclass: Object

As -postln, but posts the compileString of the receiver.

.error

Prepends an error banner and posts the string.

.warn

Prepends a warning banner and posts the string.

.inform

Legacy method (although due to widespread use, it will not be removed). This is identical to postln.

Interpreting strings as code

.compile

Compiles a String containing legal SuperCollider code and returns a Function.

.interpret

Compile and execute a String containing legal SuperCollider code, returning the result.

.interpretPrint

Compile, execute and print the result of a String containing legal SuperCollider code.

Converting strings

.asCompileString

Returns a String formatted for compiling.

.asSymbol

Return a Symbol derived from the String.

.asInteger

Return an Integer derived from the String. Strings beginning with non-numeric characters return 0.

.asFloat

Return a Float derived from the String. Strings beginning with non-numeric characters return 0.

.asSecs(maxDays: 365)

Return a Float based on converting a time string in format (ddd):hh:mm:ss.sss. This is the inverse method to SimpleNumber: -asTimeString.

Concatenate strings

++(anObject)

Return a concatenation of the two strings.

+(anObject)

Return a concatenation of the two strings with a space between them.

+/+(path)

Concatenates this and path, as components of a filesystem path on the host operating system. The strings are joined to avoid duplicate path separators.

If this ends with a path separator and path begins with one, then the separator in path is dropped. If there is a path separator on either side, this has the same effect as using ++. If neither side has a path separator, the platform's preferred separator ('\' on Windows, '/' otherwise) is added.

Returns this and path concatenated. If path was a PathName, the result is a PathName; otherwise, it is a String.

Arguments:

path

Any object that can be converted to a string. Typically, either a String, Symbol, or PathName.

.catArgs( ... items)

Concatenate this string with the following args.

.scatArgs( ... items)

Same as -catArgs, but with spaces in between.

.ccatArgs( ... items)

Same as -catArgs, but with commas in between.

.catList(list)

.scatList(list)

.ccatList(list)

As -catArgs, -scatArgs and -ccatArgs above, but takes a Collection (usually a List or an Array) as an argument.

Regular expressions

The String class provides access to the boost library's regular expression functions. Boost's default uses Perl settings. (Currently, there is no hook to override the regex style.) Syntax details may be found at https://www.boost.org/doc/libs/1_69_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html.

Note carefully the argument order:

findRegexp follows the pattern established by String: -find, where the receiver is the string to be searched. matchRegexp follows the pattern of matchItem, where the receiver is the pattern to match and the first argument is the object to be tested. This is a common source of confusion, but it is based on this precedent.

.matchRegexp(string, start: 0, end)

Perl regular expression matching (see String: Regular expressions). Returns true if the receiver (a regular expression pattern) matches the string passed to it. The start is an offset where to start searching in the string (default: 0), end where to stop.

NOTE: This is regexp.matchRegexp(stringToSearch) and not the other way around! See above: String: Regular expressions.

.findRegexp(regexp, offset: 0)

Perl regular expression search (see String: Regular expressions). This method searches exhaustively for matches and collects them into an array of pairs, in the format [character index, matching string].

"Leftmost largest match": As in most flavors of regular expressions, * and + are greedy; if it is possible to have more than one overlapping match for a part of the regular expression, the match list will include only the leftmost and largest of them. In "foobar".findRegexp("o+"), "o+" may potentially have three matches: "o" at index 1 (second character), "o" at index 2, and "oo" at index 1. findRegexp will return only the last of these ("oo"), because it begins in the leftmost-possible matching position, and it is the longest possible match at that position.

Note, though, that parentheses for grouping (a "marked sub-expression" or "capturing group") will produce a separate result: "aaa".findRegexp("(a+)"); appears to produce duplicated results [ [ 0, aaa ], [ 0, aaa ] ], but this is because the first match is for the parentheses and the second is for a+.

To see the marked sub-expression results more clearly, consider:

"oobar" matches the entire regular expression. "oo" and "bar" match the first and second parenthesized sub-expressions, respectively.

Returns:

A nested array, where each sub-array is a pair, [character index, matching string]. If there are no matches, an empty array.

.findAllRegexp(string, offset: 0)

Like -findAll, but use regular expressions (see String: Regular expressions). Unlike findRegexp, it returns only the indices of the matches: string.findAllRegexp(regexp) returns the same as string.findRegexp(regexp).flop.at(0).

Returns:

An array of integer character indices pointing to all the possible matches.

.findRegexpAt(regexp, offset: 0)

Match a regular expression (see String: Regular expressions) at the given offset, returning the match and the length of the match in an Array, or nil if it doesn't match. The match must begin right at the offset.

Returns:

An array [matching string, length] if a match is found at the specified offset; nil if the offset doesn't match.

Searching strings

.find(string, ignoreCase: false, offset: 0)

Returns the index of the string in the receiver, or nil if not found. If ignoreCase is true, find makes no difference between uppercase and lowercase letters. The offset is the point in the string where the search begins. string may be a String or a Char.

.findBackwards(string, ignoreCase: false, offset: 2147483646)

Same like -find, but starts at the end of the string.

.findAll(string, ignoreCase: false, offset: 0)

Returns the indices of the string in the receiver, or nil if not found.

.contains(string, offset: 0)

Returns a Boolean indicating if the String contains string.

.containsi(string, offset: 0)

Same as -contains, but case insensitive.

.containsStringAt(index, string)

Returns a Boolean indicating if the String contains string beginning at the specified index.

.icontainsStringAt(index, string)

Same as -containsStringAt, but case insensitive.

.beginsWith(string)

.endsWith(string)

Returns true if this string begins/ends with the specified other string.

Arguments:

string

The other string

Returns:

Manipulating strings

.rotate(n: 1)

Rotate the string by n steps.

.scramble

Randomize the order of characters in the string.

.replace(find, replace: "")

Like -tr, but with Strings as well as Chars as arguments.

.format( ... items)

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 \\% .

.escapeChar(charToEscape)

Add the escape character (\) before any character of your choice.

.quote

Return this string enclosed in double-quote ( " ) characters.

.zeroPad

Return this string enclosed in space characters.

.underlined(char: $-)

Return this string followed by dashes in the next line ( - ).

.tr(from, to)

Transliteration. Replace all instances of from with to.

.padLeft(size, string: " ")

.padRight(size, string: " ")

Pad this string with string so it fills size character.

Arguments:

size

Number of characters to fill

string

Padding string

.toUpper

Return this string with uppercase letters.

.toLower

Return this string with lowercase letters.

.stripRTF

Returns a new String with all RTF formatting removed.

.split(separator: $/)

Returns an Array of Strings split at the separator. The separator is a Char, and is not included in the output array.

Stream support

.printOn(stream)

Print the String on stream.

.storeOn(stream)

Same as -printOn, but formatted -asCompileString.

Unix Support

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:

It is however possible to execute complex commands:

Also on os x applescript can be called via osascript:

Should you need an environment variable to persist you can use -setenv.

NOTE: Despite the fact that the method is called 'unixCmd', it does work in Windows. The string must be a DOS command, however: "dir" rather than "ls" for instance.

.unixCmd(action, postOutput: true)

Execute a UNIX command asynchronously using the standard shell (sh).

Arguments:

action

A Function that is called when the process has exited. It is passed two arguments: the exit code and pid of the exited process.

postOutput

A Boolean that controls whether or not the output of the process is displayed in the post window.

Returns:

An Integer - the pid of the newly created process. Use Integer: -pidRunning to test if a process is alive.

Discussion:

Example:

.unixCmdGetStdOut(maxLineLength: 1024)

Similar to -unixCmd except that the stdout of the process is returned (synchronously) rather than sent to the post window.

.systemCmd

Executes a UNIX command synchronously using the standard shell (sh).

Returns:

Error code of the UNIX command

.runInTerminal(shell: "/bin/sh")

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Collections/linux/extString_linux.sc

Execute the String in a new terminal window (asynchronously).

Arguments:

shell

The shell used to execute the string.

Discussion:

NOTE: On macOS and Linux, the string is incorporated into a temporary script file and executed using the shell.

NOTE: On Linux, it is possible to choose a specific terminal emulator to be used, otherwise sclang tries to find one by itself. See LinuxPlatform: *runInTerminalCmd.

Example:

.setenv(value)

Set the environment variable indicated in the string to equal the String value. This value will persist until it is changed or SC is quit. Note that if value is a path you may need to call -standardizePath on it.

.getenv

Returns the value contained in the environment variable indicated by the String.

.unsetenv

Set the environment variable to nil.

.mkdir

Make a directory from the given path location.

.pathMatch

Returns an Array containing all paths matching this String. Wildcards apply, non-recursive.

.load

Load and execute the file at the path represented by the receiver.

.loadPaths(warn: true, action)

Perform -pathMatch on this String, then load and execute all paths in the resultant Array.

Arguments:

warn

Post a warning if path doesn't point to any file.

action

If a function is passed, it is called with each path as argument.

.loadRelative(warn: true, action)

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. This can be used e.g. to load initialization code from files in the same folder.

Arguments:

warn

Warn if a file is not found.

action

A function that is called for each file path that is found.

.resolveRelative

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.

.standardizePath

Expand ~ to your home directory, and resolve aliases on macOS. See PathName for more complex needs. See File: *realpath if you want to resolve symlinks.

.openOS

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Collections/linux/extString_linux.sc

Open file, directory or URL via the operating system. On macOS this is implemented via open, on Linux via xdg-open and on Windows via start.

Pathname Support

Also see -+/+ for path concatenation.

The term "path separator" is a platform-independent term for the character(s) that can be used to separate components of a path. On Windows, both forward slash "/" and backward slash "\\" are path separators. On POSIX-based systems like macOS and Linux, only forward slash is allowed.

.shellQuote

Return a new string suitable for use as a filename in a shell command, by enclosing it in single quotes ( ' ). If the string contains any single quotes they will be escaped.

Discussion:

You should use this method on a path before embedding it in a string executed by -unixCmd or -systemCmd.

NOTE: This works well with shells such as bash, other shells might need different quotation/escaping. Apart from usage in the construction of shell commands, escaping is not needed for paths passed to methods like pathMatch(path) or File.open(path).

.absolutePath

.asAbsolutePath

Return this path as an absolute path by prefixing it with File: *getcwd if necessary.

.asRelativePath(relativeTo)

Return this path as relative to the specified path.

Arguments:

relativeTo

The path to make this path relative to.

.withTrailingSlash

Appends a path separator if one is not already present.

.withoutTrailingSlash

Removes a trailing path separator if one is present.

.basename

Return the filename from a Unix path.

.dirname

Return the directory name from a Unix path.

.splitext

Split off the extension from a filename or path and return both in an Array as [path or filename, extension].

YAML and JSON parsing

.parseYAML

Parse this string as YAML/JSON.

Returns:

A nested structure of Arrays (for sequences), Dictionaries (for maps) and Strings (for scalars).

.parseYAMLFile

Same as parseYAML but parse a file directly instead of a string. This is faster than reading a file into a string and then parse it.

.parseJSON

This method is currently just an alias for -parseYAML, in the future it will only accept valid JSON.

Returns:

A nested structure of Arrays (for sequences), Dictionaries (for maps) and Strings (for scalars).

.parseJSONFile

This method is currently just an alias for -parseYAMLFile, in the future it will only accept valid JSON files.

Document Support

.newTextWindow(title: "Untitled", makeListener: false)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Create a new Document with this.

.openDocument(selectionStart: 0, selectionLength: 0)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Create a new Document from the path corresponding to this. The selection arguments will preselect the indicated range in the new window. Returns this.

.findHelpFile

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Returns the path for the helpfile named this, if it exists, else returns nil.

.help

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Performs -findHelpFile on this, and opens the file it if it exists, otherwise opens the main helpfile.

Misc methods

.inspectorClass

Returns class StringInspector.

Drawing Support

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.

See also: Window, UserView, Color, and Pen.

NOTE: for cross-platform GUIs, use Pen.stringAtPoint, Pen.stringInRect, Pen.stringCenteredIn, Pen.stringLeftJustIn, Pen.stringRightJustIn instead.

.draw

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Draws the String at the current 0@0 Point. If not transformations of the graphics state have taken place this will be the upper left corner of the window. See also Pen.

.drawAtPoint(point, font, color)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Draws the String at the given Point using the Font and Color specified.

.drawInRect(rect, font, color)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Draws the String into the given Rect using the Font and Color specified.

.drawCenteredIn(rect, font, color)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Draws the String into the given Rect using the Font and Color specified.

.drawLeftJustIn(rect, font, color)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Draws the String into the given Rect using the Font and Color specified.

.drawRightJustIn(rect, font, color)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Draws the String into the given Rect using the Font and Color specified.

.bounds(font)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

Tries to return a Rect with the size needed to fit this string if drawn with given font.

Arguments:

font

A Font

Extensions by SCDoc

.stripWhiteSpace

From extension in /usr/local/share/SuperCollider/SCClassLibrary/SCDoc/SCDoc.sc

Strips whitespace at the beginning and end of the string.

Returns:

The stripped string

.unixCmdGetStdOutLines

From extension in /usr/local/share/SuperCollider/SCClassLibrary/SCDoc/SCDoc.sc

Like -unixCmdGetStdOut but returns the lines in an Array instead.

Returns:

an Array of each line of output

Inherited instance methods

Undocumented instance methods

.asDefName

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/asDefName.sc

.asMenuAction

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/Base/Menu.sc

.asOSCArgArray

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extConvertToOSC.sc

.asOSCArgEmbeddedArray(array)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/Control/extConvertToOSC.sc

.asString

.codegen_UGenCtorArg(stream)

.die( ... culprits)

.exclude

.fformat( ... args)

.findHelpFileOrElse

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

.gethostbyname

.guiClass

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/tools/guicrucial/gui.sc

.include

.insert(index, string)

.isString

.multiChannelPerform(selector ... args)

.notemidi

From extension in /usr/local/share/SuperCollider/Extensions/SC3plugins/LoopBufUGens/classes/LJP Classes/Extensions/midinote.sc

.openHTMLFile(selectionStart: 0, selectionLength: 0)

From extension in /usr/local/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Collections/StringPlusGUI.sc

.performBinaryOpOnComplex(aSelector, aComplex)

.performBinaryOpOnSimpleNumber(aSelector, aNumber)

.realPath

.stripHTML

.ugenCodeString(ugenIndex, isDecl, inputNames: [ ], inputStrings: [ ])

.wrapExtend(size)