Binary strings: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 21: Line 21:
Possible contexts of use: compression algorithms (like [[LZW compression]]), L-systems (manipulation of symbols), many more.
Possible contexts of use: compression algorithms (like [[LZW compression]]), L-systems (manipulation of symbols), many more.
<br><br>
<br><br>

=={{header|11l}}==
=={{header|11l}}==
<syntaxhighlight lang=11l>V x = Bytes(‘abc’)
<syntaxhighlight lang="11l">V x = Bytes(‘abc’)
print(x[0])</syntaxhighlight>
print(x[0])</syntaxhighlight>


Line 30: Line 29:
97
97
</pre>
</pre>

=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
The 8086 has built-in support for handling byte and word strings, using <code>DS:SI</code> and <code>ES:DI</code> as the source and destination pointers, respectively. String functions can either auto-increment or auto-decrement the pointers held in these registers; the '''direction flag''' determines which one takes place. (<code>CLD</code> for auto-inc, <code>STD</code> for auto-dec.)
The 8086 has built-in support for handling byte and word strings, using <code>DS:SI</code> and <code>ES:DI</code> as the source and destination pointers, respectively. String functions can either auto-increment or auto-decrement the pointers held in these registers; the '''direction flag''' determines which one takes place. (<code>CLD</code> for auto-inc, <code>STD</code> for auto-dec.)
Line 36: Line 34:
===Copying strings===
===Copying strings===
This is a "deep copy," i.e. after this you will have a duplicate of the string "Hello" in two separate memory locations, not just a pointer to the original stored elsewhere.
This is a "deep copy," i.e. after this you will have a duplicate of the string "Hello" in two separate memory locations, not just a pointer to the original stored elsewhere.
<syntaxhighlight lang=asm>;this code assumes that both DS and ES point to the correct segments.
<syntaxhighlight lang="asm">;this code assumes that both DS and ES point to the correct segments.
cld
cld
mov si,offset TestMessage
mov si,offset TestMessage
Line 50: Line 48:


===Checking if a particular byte exists===
===Checking if a particular byte exists===
<syntaxhighlight lang=asm>;this code assumes that ES points to the correct segment.
<syntaxhighlight lang="asm">;this code assumes that ES points to the correct segment.
cld
cld
mov di,offset TestMessage
mov di,offset TestMessage
Line 63: Line 61:


===Compare two strings===
===Compare two strings===
<syntaxhighlight lang=asm>;this code assumes that both DS and ES point to the correct segments.
<syntaxhighlight lang="asm">;this code assumes that both DS and ES point to the correct segments.
cld
cld
mov si,offset foo
mov si,offset foo
Line 77: Line 75:
foo byte "test"
foo byte "test"
bar byte "test"</syntaxhighlight>
bar byte "test"</syntaxhighlight>

=={{header|Ada}}==
=={{header|Ada}}==
Ada has native support for single dimensioned arrays, which provide all specified operations. String is a case of array. The array of bytes is predefined in Ada in the package System.Storage_Elements ([http://www.adaic.org/standards/05rm/html/RM-13-7-1.html LRM 13.7.1]). Storage_Element is substitute for byte.
Ada has native support for single dimensioned arrays, which provide all specified operations. String is a case of array. The array of bytes is predefined in Ada in the package System.Storage_Elements ([http://www.adaic.org/standards/05rm/html/RM-13-7-1.html LRM 13.7.1]). Storage_Element is substitute for byte.


<syntaxhighlight lang=Ada>declare
<syntaxhighlight lang="ada">declare
Data : Storage_Array (1..20); -- Data created
Data : Storage_Array (1..20); -- Data created
begin
begin
Line 99: Line 96:
end; -- Data destructed</syntaxhighlight>
end; -- Data destructed</syntaxhighlight>
Storage_Array is "binary string" used for memory representation. For stream-oriented I/O communication Ada provides alternative "binary string" called Stream_Element_Array ([http://www.adaic.org/standards/05rm/html/RM-13-13-1.html LRM 13.13.1]). When dealing with octets of bits, programmers are encouraged to provide a data type of their own to ensure that the byte is exactly 8 bits length. For example:
Storage_Array is "binary string" used for memory representation. For stream-oriented I/O communication Ada provides alternative "binary string" called Stream_Element_Array ([http://www.adaic.org/standards/05rm/html/RM-13-13-1.html LRM 13.13.1]). When dealing with octets of bits, programmers are encouraged to provide a data type of their own to ensure that the byte is exactly 8 bits length. For example:
<syntaxhighlight lang=Ada>type Octet is mod 2**8;
<syntaxhighlight lang="ada">type Octet is mod 2**8;
for Octet'Size use 8;
for Octet'Size use 8;
type Octet_String is array (Positive range <>) of Octet;</syntaxhighlight>
type Octet_String is array (Positive range <>) of Octet;</syntaxhighlight>
Alternatively:
Alternatively:
<syntaxhighlight lang=Ada>with Interfaces; use Interfaces;
<syntaxhighlight lang="ada">with Interfaces; use Interfaces;
...
...
type Octet is new Interfaces.Unsigned_8;
type Octet is new Interfaces.Unsigned_8;
type Octet_String is array (Positive range <>) of Octet;</syntaxhighlight>
type Octet_String is array (Positive range <>) of Octet;</syntaxhighlight>
Note that all of these types will have all operations described above.
Note that all of these types will have all operations described above.

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|Tcl}}
{{trans|Tcl}}
Line 115: Line 111:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has no FORMATted transput}} -->
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has no FORMATted transput}} -->
<syntaxhighlight lang=algol68># String creation #
<syntaxhighlight lang="algol68"># String creation #
STRING a,b,c,d,e,f,g,h,i,j,l,r;
STRING a,b,c,d,e,f,g,h,i,j,l,r;
a := "hello world";
a := "hello world";
Line 229: Line 225:
7th byte in CPU word is: w
7th byte in CPU word is: w
</pre>
</pre>

=={{header|Arturo}}==
=={{header|Arturo}}==


<syntaxhighlight lang=rebol>; creation
<syntaxhighlight lang="rebol">; creation
x: "this is a string"
x: "this is a string"
y: "this is another string"
y: "this is another string"
Line 276: Line 271:
this is a string!now this is another string too
this is a string!now this is another string too
This is a sTring!now This is anoTher sTring Too</pre>
This is a sTring!now This is anoTher sTring Too</pre>

=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=AWK>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f


BEGIN {
BEGIN {
Line 325: Line 319:
d=<123 abc @456 789>
d=<123 abc @456 789>
</pre>
</pre>

=={{header|BASIC}}==
=={{header|BASIC}}==


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang=ApplesoftBasic>REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM)
<syntaxhighlight lang="applesoftbasic">REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM)
A$ = "STRING" : REM CREATION
A$ = "STRING" : REM CREATION
A$ = "" : REM DESTRUCTION
A$ = "" : REM DESTRUCTION
Line 360: Line 353:
==={{header|GW-BASIC}}===
==={{header|GW-BASIC}}===
Also works in QBASIC, QuickBASIC, VB-DOS and PDS 7.1
Also works in QBASIC, QuickBASIC, VB-DOS and PDS 7.1
<syntaxhighlight lang=QBASIC>
<syntaxhighlight lang="qbasic">
10 ' SAVE"BINSTR", A
10 ' SAVE"BINSTR", A
20 ' This program does string manipulation
20 ' This program does string manipulation
Line 377: Line 370:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS-BASIC>100 RANDOMIZE
<syntaxhighlight lang="is-basic">100 RANDOMIZE
110 REM create two strings
110 REM create two strings
120 LET S$="Hello":LET T$="Bob"
120 LET S$="Hello":LET T$="Bob"
Line 392: Line 385:


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
<syntaxhighlight lang=text>
<syntaxhighlight lang="text">
'STRING CREATION AND DESTRUCTION
'STRING CREATION AND DESTRUCTION
string A
string A
Line 437: Line 430:


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang=basic>10 REM create two strings
<syntaxhighlight lang="basic">10 REM create two strings
20 LET s$ = "Hello"
20 LET s$ = "Hello"
30 LET t$ = "Bob"
30 LET t$ = "Bob"
Line 450: Line 443:
120 REM print characters 2 to 4 of a string (a substring)
120 REM print characters 2 to 4 of a string (a substring)
130 PRINT s$(2 TO 4)</syntaxhighlight>
130 PRINT s$(2 TO 4)</syntaxhighlight>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<syntaxhighlight lang=bbcbasic> A$ = CHR$(0) + CHR$(1) + CHR$(254) + CHR$(255) : REM assignment
<syntaxhighlight lang="bbcbasic"> A$ = CHR$(0) + CHR$(1) + CHR$(254) + CHR$(255) : REM assignment
B$ = A$ : REM clone / copy
B$ = A$ : REM clone / copy
IF A$ = B$ THEN PRINT "Strings are equal" : REM comparison
IF A$ = B$ THEN PRINT "Strings are equal" : REM comparison
Line 468: Line 460:
UNTIL I% = 0
UNTIL I% = 0
</syntaxhighlight>
</syntaxhighlight>


=={{header|BQN}}==
=={{header|BQN}}==


Line 477: Line 467:


* Example binary string creation
* Example binary string creation
<syntaxhighlight lang=bqn> name ← ""</syntaxhighlight>
<syntaxhighlight lang="bqn"> name ← ""</syntaxhighlight>


* Example binary string deletion: effectively replaces the data with an integer, removing it from an accessible name.
* Example binary string deletion: effectively replaces the data with an integer, removing it from an accessible name.
<syntaxhighlight lang=bqn> name ↩ 0</syntaxhighlight>
<syntaxhighlight lang="bqn"> name ↩ 0</syntaxhighlight>


* Example binary string assignment
* Example binary string assignment
<syntaxhighlight lang=bqn> name ← "value"</syntaxhighlight>
<syntaxhighlight lang="bqn"> name ← "value"</syntaxhighlight>


* Example binary string comparison
* Example binary string comparison
<syntaxhighlight lang=bqn> name1 ≡ name2</syntaxhighlight>
<syntaxhighlight lang="bqn"> name1 ≡ name2</syntaxhighlight>


* Example binary string cloning and copying
* Example binary string cloning and copying
<syntaxhighlight lang=bqn> name1 ← "example"
<syntaxhighlight lang="bqn"> name1 ← "example"
name2 ← name1</syntaxhighlight>
name2 ← name1</syntaxhighlight>


* Example check if a binary string is empty
* Example check if a binary string is empty
<syntaxhighlight lang=bqn> 0=≠string</syntaxhighlight>
<syntaxhighlight lang="bqn"> 0=≠string</syntaxhighlight>


* Example apppend a byte to a binary string
* Example apppend a byte to a binary string
<syntaxhighlight lang=bqn> string ← "example"
<syntaxhighlight lang="bqn"> string ← "example"
byte ← @
byte ← @
string ∾↩ byte</syntaxhighlight>
string ∾↩ byte</syntaxhighlight>


* Extract a substring from a binary string
* Extract a substring from a binary string
<syntaxhighlight lang=bqn> 3↓¯5↓"The quick brown fox runs..."</syntaxhighlight>
<syntaxhighlight lang="bqn"> 3↓¯5↓"The quick brown fox runs..."</syntaxhighlight>


* Join strings
* Join strings
<syntaxhighlight lang=bqn> "string1"∾"string2"</syntaxhighlight>
<syntaxhighlight lang="bqn"> "string1"∾"string2"</syntaxhighlight>


Note also: given an integer n, the corresponding byte value may be added to the null character <code>@</code> to get the character at that codepoint. This works due to BQN's character arithmetic.
Note also: given an integer n, the corresponding byte value may be added to the null character <code>@</code> to get the character at that codepoint. This works due to BQN's character arithmetic.
<syntaxhighlight lang=bqn> n + @</syntaxhighlight>
<syntaxhighlight lang="bqn"> n + @</syntaxhighlight>


Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
<syntaxhighlight lang=bqn>1‿0‿255 + @</syntaxhighlight>
<syntaxhighlight lang="bqn">1‿0‿255 + @</syntaxhighlight>

=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 651: Line 640:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>
=={{header|C sharp|C#}}==
{{works with|C sharp|3.0}}


<syntaxhighlight lang="csharp">using System;

class Program
{
static void Main()
{
//string creation
var x = "hello world";

//# mark string for garbage collection
x = null;

//# string assignment with a null byte
x = "ab\0";
Console.WriteLine(x);
Console.WriteLine(x.Length); // 3

//# string comparison
if (x == "hello")
Console.WriteLine("equal");
else
Console.WriteLine("not equal");

if (x.CompareTo("bc") == -1)
Console.WriteLine("x is lexicographically less than 'bc'");

//# string cloning
var c = new char[3];
x.CopyTo(0, c, 0, 3);
object objecty = new string(c);
var y = new string(c);

Console.WriteLine(x == y); //same as string.equals
Console.WriteLine(x.Equals(y)); //it overrides object.Equals

Console.WriteLine(x == objecty); //uses object.Equals, return false

//# check if empty
var empty = "";
string nullString = null;
var whitespace = " ";
if (nullString == null && empty == string.Empty &&
string.IsNullOrEmpty(nullString) && string.IsNullOrEmpty(empty) &&
string.IsNullOrWhiteSpace(nullString) && string.IsNullOrWhiteSpace(empty) &&
string.IsNullOrWhiteSpace(whitespace))
Console.WriteLine("Strings are null, empty or whitespace");

//# append a byte
x = "helloworld";
x += (char)83;
Console.WriteLine(x);

//# substring
var slice = x.Substring(5, 5);
Console.WriteLine(slice);

//# replace bytes
var greeting = x.Replace("worldS", "");
Console.WriteLine(greeting);

//# join strings
var join = greeting + " " + slice;
Console.WriteLine(join);
}
}</syntaxhighlight>
=={{header|C++}}==
=={{header|C++}}==
<syntaxhighlight lang=cpp>#include <iomanip>
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <iostream>


Line 729: Line 785:
hello
hello
hello world</pre>
hello world</pre>

=={{header|C sharp|C#}}==
{{works with|C sharp|3.0}}

<syntaxhighlight lang=csharp>using System;

class Program
{
static void Main()
{
//string creation
var x = "hello world";

//# mark string for garbage collection
x = null;

//# string assignment with a null byte
x = "ab\0";
Console.WriteLine(x);
Console.WriteLine(x.Length); // 3

//# string comparison
if (x == "hello")
Console.WriteLine("equal");
else
Console.WriteLine("not equal");

if (x.CompareTo("bc") == -1)
Console.WriteLine("x is lexicographically less than 'bc'");

//# string cloning
var c = new char[3];
x.CopyTo(0, c, 0, 3);
object objecty = new string(c);
var y = new string(c);

Console.WriteLine(x == y); //same as string.equals
Console.WriteLine(x.Equals(y)); //it overrides object.Equals

Console.WriteLine(x == objecty); //uses object.Equals, return false

//# check if empty
var empty = "";
string nullString = null;
var whitespace = " ";
if (nullString == null && empty == string.Empty &&
string.IsNullOrEmpty(nullString) && string.IsNullOrEmpty(empty) &&
string.IsNullOrWhiteSpace(nullString) && string.IsNullOrWhiteSpace(empty) &&
string.IsNullOrWhiteSpace(whitespace))
Console.WriteLine("Strings are null, empty or whitespace");

//# append a byte
x = "helloworld";
x += (char)83;
Console.WriteLine(x);

//# substring
var slice = x.Substring(5, 5);
Console.WriteLine(slice);

//# replace bytes
var greeting = x.Replace("worldS", "");
Console.WriteLine(greeting);

//# join strings
var join = greeting + " " + slice;
Console.WriteLine(join);
}
}</syntaxhighlight>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
String creation (garbage collection will handle its destruction)
String creation (garbage collection will handle its destruction)
using the string as an atom and casting a character list to a string
using the string as an atom and casting a character list to a string
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
"string"
"string"
(coerce '(#\s #\t #\r #\i #\n #\g) 'string)
(coerce '(#\s #\t #\r #\i #\n #\g) 'string)
Line 808: Line 794:


String assignment
String assignment
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(defvar *string* "string")
(defvar *string* "string")
</syntaxhighlight>
</syntaxhighlight>


comparing two string
comparing two string
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(equal "string" "string")
(equal "string" "string")
</syntaxhighlight>
</syntaxhighlight>


copy a string
copy a string
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(copy-seq "string")
(copy-seq "string")
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(defun string-empty-p (string)
(defun string-empty-p (string)
(zerop (length string)))</syntaxhighlight>
(zerop (length string)))</syntaxhighlight>


<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(concatenate 'string "string" "b")
(concatenate 'string "string" "b")
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(subseq "string" 2 6)
(subseq "string" 2 6)
"ring"
"ring"
Line 839: Line 825:


joining strings works in the same way as appending bytes
joining strings works in the same way as appending bytes

=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE NpctBinaryString;
MODULE NpctBinaryString;
IMPORT StdLog,Strings;
IMPORT StdLog,Strings;
Line 922: Line 907:
pStr + '.' + pAux:>First string.Second String
pStr + '.' + pAux:>First string.Second String
</pre>
</pre>

=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>void main() /*@safe*/ {
<syntaxhighlight lang="d">void main() /*@safe*/ {
import std.array: empty, replace;
import std.array: empty, replace;
import std.string: representation, assumeUTF;
import std.string: representation, assumeUTF;
Line 969: Line 953:
ubyte[] str3 = str1 ~ str2;
ubyte[] str3 = str1 ~ str2;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Déjà Vu}}==

Déjà Vu has a <code>blob</code> type, which is much like Python 3's <code>bytearray</code>. They are used for dealing with binary data in the standard library, and works basically like a list, except it can only have integer numbers from 0 to 255 as elements, pushing and popping is not supported, and can be resized to any size in a single step.

<syntaxhighlight lang=dejavu>local :b make-blob 10 #ten bytes of initial size
set-to b 0 255
!. get-from b 0 #prints 255
!. b #prints (blob:ff000000000000000000)
local :b2 make-blob 3
set-to b2 0 97
set-to b2 1 98
set-to b2 2 99
!. b #prints (blob:"abc")
!. !encode!utf-8 b #prints "abc"
</syntaxhighlight>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program Binary_strings;
program Binary_strings;


Line 1,076: Line 1,044:
hello
hello
hello world</pre>
hello world</pre>
=={{header|Déjà Vu}}==


Déjà Vu has a <code>blob</code> type, which is much like Python 3's <code>bytearray</code>. They are used for dealing with binary data in the standard library, and works basically like a list, except it can only have integer numbers from 0 to 255 as elements, pushing and popping is not supported, and can be resized to any size in a single step.

<syntaxhighlight lang="dejavu">local :b make-blob 10 #ten bytes of initial size
set-to b 0 255
!. get-from b 0 #prints 255
!. b #prints (blob:ff000000000000000000)
local :b2 make-blob 3
set-to b2 0 97
set-to b2 1 98
set-to b2 2 99
!. b #prints (blob:"abc")
!. !encode!utf-8 b #prints "abc"
</syntaxhighlight>
=={{header|E}}==
=={{header|E}}==


Line 1,085: Line 1,067:
To work with binary strings we must first have a byte type; this is a place where E shows its Java roots (to be fixed).
To work with binary strings we must first have a byte type; this is a place where E shows its Java roots (to be fixed).


<syntaxhighlight lang=e>? def int8 := <type:java.lang.Byte>
<syntaxhighlight lang="e">? def int8 := <type:java.lang.Byte>
# value: int8</syntaxhighlight>
# value: int8</syntaxhighlight>


<ol>
<ol>
<li>There are several ways to create a FlexList; perhaps the simplest is:
<li>There are several ways to create a FlexList; perhaps the simplest is:
<syntaxhighlight lang=e>? def bstr := [].diverge(int8)
<syntaxhighlight lang="e">? def bstr := [].diverge(int8)
# value: [].diverge()
# value: [].diverge()


Line 1,101: Line 1,083:
</li><li>There is no specific assignment between FlexLists; a reference may be passed in the usual manner, or the contents of one could be copied to another as shown below.
</li><li>There is no specific assignment between FlexLists; a reference may be passed in the usual manner, or the contents of one could be copied to another as shown below.
</li><li>There is no comparison operation between FlexLists (since it would not be a stable ordering <!-- XXX cite? -->), but there is between ConstLists.
</li><li>There is no comparison operation between FlexLists (since it would not be a stable ordering <!-- XXX cite? -->), but there is between ConstLists.
<syntaxhighlight lang=e>? bstr1.snapshot() < bstr2.snapshot()
<syntaxhighlight lang="e">? bstr1.snapshot() < bstr2.snapshot()
# value: false</syntaxhighlight>
# value: false</syntaxhighlight>
</li><li>To make an independent copy of a FlexList, simply <code>.diverge()</code> it again.
</li><li>To make an independent copy of a FlexList, simply <code>.diverge()</code> it again.
</li><li><syntaxhighlight lang=e>? bstr1.size().isZero()
</li><li><syntaxhighlight lang="e">? bstr1.size().isZero()
# value: false
# value: false


Line 1,110: Line 1,092:
# value: true</syntaxhighlight>
# value: true</syntaxhighlight>
</li><li>Appending a single element to a FlexList is done by <code>.push(<var>x</var>)</code>:
</li><li>Appending a single element to a FlexList is done by <code>.push(<var>x</var>)</code>:
<syntaxhighlight lang=e>? bstr.push(0)
<syntaxhighlight lang="e">? bstr.push(0)
? bstr
? bstr
# value: [0].diverge()</syntaxhighlight>
# value: [0].diverge()</syntaxhighlight>
</li><li>Substrings, or ''runs'', are always immutable and specified as start-end indexes (as opposed to first-last or start-count). Or, one can copy an arbitrary portion of one list into another using <code>replace(<var>target range</var>, <var>source list</var>, <var>source range</var>)</code>.
</li><li>Substrings, or ''runs'', are always immutable and specified as start-end indexes (as opposed to first-last or start-count). Or, one can copy an arbitrary portion of one list into another using <code>replace(<var>target range</var>, <var>source list</var>, <var>source range</var>)</code>.
<syntaxhighlight lang=e>? bstr1(1, 2)
<syntaxhighlight lang="e">? bstr1(1, 2)
# value: [2]
# value: [2]


Line 1,121: Line 1,103:
# value: [2, 3].diverge()</syntaxhighlight>
# value: [2, 3].diverge()</syntaxhighlight>
</li><li>Replacing must be written as an explicit loop; there is no built-in operation (though there is for character strings).
</li><li>Replacing must be written as an explicit loop; there is no built-in operation (though there is for character strings).
<syntaxhighlight lang=e>? for i => byte ? (byte == 2) in bstr2 { bstr2[i] := -1 }
<syntaxhighlight lang="e">? for i => byte ? (byte == 2) in bstr2 { bstr2[i] := -1 }
? bstr2
? bstr2
# value: [-127, -1, 3].diverge()</syntaxhighlight>
# value: [-127, -1, 3].diverge()</syntaxhighlight>
</li><li>Two lists can be concatenated into a ConstList by <code>+</code>: <code>bstr1 + bstr2</code>. <code>append</code> appends on the end of a FlexList, and <code>replace</code> can be used to insert at the beginning or anywhere inside.
</li><li>Two lists can be concatenated into a ConstList by <code>+</code>: <code>bstr1 + bstr2</code>. <code>append</code> appends on the end of a FlexList, and <code>replace</code> can be used to insert at the beginning or anywhere inside.
<syntaxhighlight lang=e>? bstr1.append(bstr2)
<syntaxhighlight lang="e">? bstr1.append(bstr2)
? bstr1
? bstr1
# value: [1, 2, 3, -127, 2, 3].diverge()</syntaxhighlight>
# value: [1, 2, 3, -127, 2, 3].diverge()</syntaxhighlight>
</li></ol>
</li></ol>

=={{header|Elixir}}==
=={{header|Elixir}}==
Note: Elixir data types are immutable.
Note: Elixir data types are immutable.
<syntaxhighlight lang=elixir># String creation
<syntaxhighlight lang="elixir"># String creation
x = "hello world"
x = "hello world"


Line 1,187: Line 1,168:
c = "orld"
c = "orld"
IO.puts a <> b <> c #=> hello world</syntaxhighlight>
IO.puts a <> b <> c #=> hello world</syntaxhighlight>

=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>-module(binary_string).
<syntaxhighlight lang="erlang">-module(binary_string).
-compile([export_all]).
-compile([export_all]).


Line 1,239: Line 1,219:
replace(Rest,Value,Replacement,<< Acc/binary, Keep >>).</syntaxhighlight>
replace(Rest,Value,Replacement,<< Acc/binary, Keep >>).</syntaxhighlight>
{{out}}
{{out}}
<syntaxhighlight lang=erlang>215> binary_string:test().
<syntaxhighlight lang="erlang">215> binary_string:test().
Creation: <<0,1,1,2,3,5,8,13>>
Creation: <<0,1,1,2,3,5,8,13>>
Copy: <<0,1,1,2,3,5,8,13>>
Copy: <<0,1,1,2,3,5,8,13>>
Line 1,249: Line 1,229:
Append: <<0,1,1,2,3,5,8,13,21>>
Append: <<0,1,1,2,3,5,8,13,21>>
Join: <<0,1,1,2,3,5,8,13,21,34,55>></syntaxhighlight>
Join: <<0,1,1,2,3,5,8,13,21,34,55>></syntaxhighlight>

=={{header|Factor}}==
=={{header|Factor}}==
Factor has a <code>byte-array</code> type which works exactly like other arrays, except only bytes can be stored in it. Comparisons on <code>byte-array</code>s (like comparisons on arrays) are lexicographic.
Factor has a <code>byte-array</code> type which works exactly like other arrays, except only bytes can be stored in it. Comparisons on <code>byte-array</code>s (like comparisons on arrays) are lexicographic.


To convert a string to a byte-array:
To convert a string to a byte-array:
<syntaxhighlight lang=factor>"Hello, byte-array!" utf8 encode .</syntaxhighlight>
<syntaxhighlight lang="factor">"Hello, byte-array!" utf8 encode .</syntaxhighlight>
<pre>
<pre>
B{
B{
Line 1,261: Line 1,240:
</pre>
</pre>
Reverse:
Reverse:
<syntaxhighlight lang=factor>B{ 147 250 150 123 } shift-jis decode .</syntaxhighlight>
<syntaxhighlight lang="factor">B{ 147 250 150 123 } shift-jis decode .</syntaxhighlight>
<pre>"日本"</pre>
<pre>"日本"</pre>

=={{header|Forth}}==
=={{header|Forth}}==
In Forth, as in Assembler, all strings are binary ie: they are simply bytes in memory. <br>
In Forth, as in Assembler, all strings are binary ie: they are simply bytes in memory. <br>
Line 1,273: Line 1,251:


<syntaxhighlight lang=forth>\ Rosetta Code Binary Strings Demo in Forth
<syntaxhighlight lang="forth">\ Rosetta Code Binary Strings Demo in Forth
\ Portions of this code are found at http://forth.sourceforge.net/mirror/toolbelt-ext/index.html
\ Portions of this code are found at http://forth.sourceforge.net/mirror/toolbelt-ext/index.html


Line 1,375: Line 1,353:
at the Forth console to see if we have satisfied the Rosetta code requirements
at the Forth console to see if we have satisfied the Rosetta code requirements


<syntaxhighlight lang=forth>\ Rosetta Code Binary String tasks Console Tests
<syntaxhighlight lang="forth">\ Rosetta Code Binary String tasks Console Tests


\ 1. String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
\ 1. String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
Line 1,502: Line 1,480:


</syntaxhighlight>
</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>
<syntaxhighlight lang="freebasic">
Dim As String cad, cad2
Dim As String cad, cad2
'creación de cadenas
'creación de cadenas
Line 1,546: Line 1,522:
Sleep
Sleep
</syntaxhighlight>
</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,647: Line 1,621:
bary
bary
</pre>
</pre>

=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=groovy>import java.nio.charset.StandardCharsets
<syntaxhighlight lang="groovy">import java.nio.charset.StandardCharsets


class MutableByteString {
class MutableByteString {
Line 1,771: Line 1,744:


Test Code
Test Code
<syntaxhighlight lang=groovy>import org.testng.Assert
<syntaxhighlight lang="groovy">import org.testng.Assert
import org.testng.annotations.Test
import org.testng.annotations.Test


Line 1,830: Line 1,803:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Haskell}}==
=={{header|Haskell}}==
Note that any of the following functions can be assigned
Note that any of the following functions can be assigned
Line 1,842: Line 1,814:
as Haskell can be somewhat intimidating to the (currently) non-
as Haskell can be somewhat intimidating to the (currently) non-
functional programmer.
functional programmer.
<syntaxhighlight lang=haskell>import Text.Regex
<syntaxhighlight lang="haskell">import Text.Regex
{- The above import is needed only for the last function.
{- The above import is needed only for the last function.
It is used there purely for readability and conciseness -}
It is used there purely for readability and conciseness -}
Line 1,852: Line 1,824:
string = "world" :: String</syntaxhighlight>
string = "world" :: String</syntaxhighlight>


<syntaxhighlight lang=haskell>{- Comparing two given strings and
<syntaxhighlight lang="haskell">{- Comparing two given strings and
returning a boolean result using a
returning a boolean result using a
simple conditional -}
simple conditional -}
Line 1,861: Line 1,833:
else False</syntaxhighlight>
else False</syntaxhighlight>


<syntaxhighlight lang=haskell>{- As strings are equivalent to lists
<syntaxhighlight lang="haskell">{- As strings are equivalent to lists
of characters in Haskell, test and
of characters in Haskell, test and
see if the given string is an empty list -}
see if the given string is an empty list -}
Line 1,870: Line 1,842:
else False</syntaxhighlight>
else False</syntaxhighlight>


<syntaxhighlight lang=haskell>{- This is the most obvious way to
<syntaxhighlight lang="haskell">{- This is the most obvious way to
append strings, using the built-in
append strings, using the built-in
(++) concatenation operator
(++) concatenation operator
Line 1,879: Line 1,851:
strAppend x y = x ++ y</syntaxhighlight>
strAppend x y = x ++ y</syntaxhighlight>


<syntaxhighlight lang=haskell>{- Take the specified number of characters
<syntaxhighlight lang="haskell">{- Take the specified number of characters
from the given string -}
from the given string -}
strExtract :: Int -> String -> String
strExtract :: Int -> String -> String
strExtract x s = take x s</syntaxhighlight>
strExtract x s = take x s</syntaxhighlight>


<syntaxhighlight lang=haskell>{- Take a certain substring, specified by
<syntaxhighlight lang="haskell">{- Take a certain substring, specified by
two integers, from the given string -}
two integers, from the given string -}
strPull :: Int -> Int -> String -> String
strPull :: Int -> Int -> String -> String
strPull x y s = take (y-x+1) (drop x s)</syntaxhighlight>
strPull x y s = take (y-x+1) (drop x s)</syntaxhighlight>


<syntaxhighlight lang=haskell>{- Much thanks to brool.com for this nice
<syntaxhighlight lang="haskell">{- Much thanks to brool.com for this nice
and elegant solution. Using an imported standard library
and elegant solution. Using an imported standard library
(Text.Regex), replace a given substring with another -}
(Text.Regex), replace a given substring with another -}
strReplace :: String -> String -> String -> String
strReplace :: String -> String -> String -> String
strReplace old new orig = subRegex (mkRegex old) orig new</syntaxhighlight>
strReplace old new orig = subRegex (mkRegex old) orig new</syntaxhighlight>

=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon strings strings are variable length and unrestricted. See [[Logical_operations#Icon_and_Unicon|Logical Operations]] for ways to manipulate strings at the bit level.
Icon and Unicon strings strings are variable length and unrestricted. See [[Logical_operations#Icon_and_Unicon|Logical Operations]] for ways to manipulate strings at the bit level.
<syntaxhighlight lang=Icon>s := "\x00" # strings can contain any value, even nulls
<syntaxhighlight lang="icon">s := "\x00" # strings can contain any value, even nulls
s := "abc" # create a string
s := "abc" # create a string
s := &null # destroy a string (garbage collect value of s; set new value to &null)
s := &null # destroy a string (garbage collect value of s; set new value to &null)
Line 1,913: Line 1,884:


The {{libheader|Icon Programming Library}} provides the procedure [http://www.cs.arizona.edu/icon/library/src/procs/strings.icn replace in strings]
The {{libheader|Icon Programming Library}} provides the procedure [http://www.cs.arizona.edu/icon/library/src/procs/strings.icn replace in strings]
<syntaxhighlight lang=Icon>procedure replace(s1, s2, s3) #: string replacement
<syntaxhighlight lang="icon">procedure replace(s1, s2, s3) #: string replacement
local result, i
local result, i


Line 1,929: Line 1,900:


end</syntaxhighlight>
end</syntaxhighlight>

=={{header|J}}==
=={{header|J}}==
J's literal data type supports arbitrary binary data (strings are binary strings by default). J's semantics are pass by value (with garbage collection) with a minor exception (mapped files).
J's literal data type supports arbitrary binary data (strings are binary strings by default). J's semantics are pass by value (with garbage collection) with a minor exception (mapped files).


* Example binary string creation
* Example binary string creation
<syntaxhighlight lang=j> name=: ''</syntaxhighlight>
<syntaxhighlight lang="j"> name=: ''</syntaxhighlight>


* Example binary string deletion (removing all references to a string allows it to be deleted, in this case we give the name a numeric value to replace its prior string value):
* Example binary string deletion (removing all references to a string allows it to be deleted, in this case we give the name a numeric value to replace its prior string value):
<syntaxhighlight lang=j> name=: 0</syntaxhighlight>
<syntaxhighlight lang="j"> name=: 0</syntaxhighlight>


* Example binary string assignment
* Example binary string assignment
<syntaxhighlight lang=j> name=: 'value'</syntaxhighlight>
<syntaxhighlight lang="j"> name=: 'value'</syntaxhighlight>


* Example binary string comparison
* Example binary string comparison
<syntaxhighlight lang=j> name1 -: name2</syntaxhighlight>
<syntaxhighlight lang="j"> name1 -: name2</syntaxhighlight>


* Example binary string cloning and copying
* Example binary string cloning and copying
<syntaxhighlight lang=j> name1=: 'example'
<syntaxhighlight lang="j"> name1=: 'example'
name2=: name1</syntaxhighlight>
name2=: name1</syntaxhighlight>


Line 1,952: Line 1,922:


* Example check if a binary string is empty
* Example check if a binary string is empty
<syntaxhighlight lang=j> 0=#string</syntaxhighlight>
<syntaxhighlight lang="j"> 0=#string</syntaxhighlight>


* Example apppend a byte to a binary string
* Example apppend a byte to a binary string
<syntaxhighlight lang=j> string=: 'example'
<syntaxhighlight lang="j"> string=: 'example'
byte=: DEL
byte=: DEL
string=: string,byte</syntaxhighlight>
string=: string,byte</syntaxhighlight>


* Extract a substring from a binary string
* Extract a substring from a binary string
<syntaxhighlight lang=j> 3{.5}.'The quick brown fox runs...'</syntaxhighlight>
<syntaxhighlight lang="j"> 3{.5}.'The quick brown fox runs...'</syntaxhighlight>


* Replace every occurrence of a byte (or a string) in a string with another string
* Replace every occurrence of a byte (or a string) in a string with another string
<syntaxhighlight lang=j>require 'strings'
<syntaxhighlight lang="j">require 'strings'
'The quick brown fox runs...' rplc ' ';' !!! '</syntaxhighlight>
'The quick brown fox runs...' rplc ' ';' !!! '</syntaxhighlight>


* Join strings
* Join strings
<syntaxhighlight lang=j> 'string1','string2'</syntaxhighlight>
<syntaxhighlight lang="j"> 'string1','string2'</syntaxhighlight>


Note also: given an integer n, the corresponding byte value may be obtained by indexing into <code>a.</code> which is the ordered array of all bytes.:
Note also: given an integer n, the corresponding byte value may be obtained by indexing into <code>a.</code> which is the ordered array of all bytes.:
<syntaxhighlight lang=j> n{a.</syntaxhighlight>
<syntaxhighlight lang="j"> n{a.</syntaxhighlight>


Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
<syntaxhighlight lang=j>1 0 255{a.</syntaxhighlight>
<syntaxhighlight lang="j">1 0 255{a.</syntaxhighlight>

=={{header|Java}}==
=={{header|Java}}==


<syntaxhighlight lang=java>import java.io.ByteArrayOutputStream;
<syntaxhighlight lang="java">import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Arrays;
Line 2,098: Line 2,067:
Test code:
Test code:


<syntaxhighlight lang=java>import static org.hamcrest.CoreMatchers.is;
<syntaxhighlight lang="java">import static org.hamcrest.CoreMatchers.is;


import java.nio.charset.StandardCharsets;
import java.nio.charset.StandardCharsets;
Line 2,158: Line 2,127:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|JavaScript}}==
=={{header|JavaScript}}==


JavaScript has native support for binary strings. All strings are "binary" and they're not zero terminated; however to be more exact you can't really see the bytes on the string, strings go from Unicode 0 to Unicode FFFF
JavaScript has native support for binary strings. All strings are "binary" and they're not zero terminated; however to be more exact you can't really see the bytes on the string, strings go from Unicode 0 to Unicode FFFF
<syntaxhighlight lang=JavaScript>//String creation
<syntaxhighlight lang="javascript">//String creation
var str='';
var str='';
//or
//or
Line 2,216: Line 2,184:
str3+str4;
str3+str4;
str.concat('\n',str4); //concantenate them</syntaxhighlight>
str.concat('\n',str4); //concantenate them</syntaxhighlight>

=={{header|jq}}==
=={{header|jq}}==


jq's strings are JSON strings and so cannot be safely used as "binary strings" in the sense of this article. The most convenient way to store a string of bytes in jq is as a jq array of integers, it being understood that jq itself does **not** provide a mechanism for guaranteeing that all the elements of a particular array are integers in the expected range.
jq's strings are JSON strings and so cannot be safely used as "binary strings" in the sense of this article. The most convenient way to store a string of bytes in jq is as a jq array of integers, it being understood that jq itself does **not** provide a mechanism for guaranteeing that all the elements of a particular array are integers in the expected range.


It is appropriate therefore to introduce a filter for verifying that an entity is an array of integers in the appropriate range:<syntaxhighlight lang=jq># If the input is a valid representation of a binary string
It is appropriate therefore to introduce a filter for verifying that an entity is an array of integers in the appropriate range:<syntaxhighlight lang="jq"># If the input is a valid representation of a binary string
# then pass it along:
# then pass it along:
def check_binary:
def check_binary:
Line 2,232: Line 2,199:
end );</syntaxhighlight>
end );</syntaxhighlight>
Examples
Examples
<syntaxhighlight lang=jq>## Creation of an entity representing an empty binary string
<syntaxhighlight lang="jq">## Creation of an entity representing an empty binary string


[]
[]
Line 2,303: Line 2,270:
if $byte == x then . + a else . + [$byte] end)
if $byte == x then . + a else . + [$byte] end)
</syntaxhighlight>
</syntaxhighlight>

=={{header|Julia}}==
=={{header|Julia}}==
{{trans|MATLAB}}
{{trans|MATLAB}}
<syntaxhighlight lang=julia>
<syntaxhighlight lang="julia">
# String assignment. Creation and garbage collection are automatic.
# String assignment. Creation and garbage collection are automatic.
a = "123\x00 abc " # strings can contain bytes that are not printable in the local font
a = "123\x00 abc " # strings can contain bytes that are not printable in the local font
Line 2,368: Line 2,334:
123 abc d456 789
123 abc d456 789
</pre>
</pre>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
Strings in Kotlin are sequences of 16-bit unicode characters and have a lot of functions built-in, including all those required by this task.
Strings in Kotlin are sequences of 16-bit unicode characters and have a lot of functions built-in, including all those required by this task.
Line 2,375: Line 2,340:


The implementation is not intended to be particularly efficient as I've sometimes delegated to the corresponding String class functions in the interests of both simplicity and brevity. Moreover, when Java 9's 'compact strings' feature is implemented, it won't even save memory as Strings which don't contain characters with code-points above 255 are apparently going to be flagged and stored internally as arrays of single bytes by the JVM, not arrays of 2 byte characters as at present.
The implementation is not intended to be particularly efficient as I've sometimes delegated to the corresponding String class functions in the interests of both simplicity and brevity. Moreover, when Java 9's 'compact strings' feature is implemented, it won't even save memory as Strings which don't contain characters with code-points above 255 are apparently going to be flagged and stored internally as arrays of single bytes by the JVM, not arrays of 2 byte characters as at present.
<syntaxhighlight lang=scala>class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
<syntaxhighlight lang="scala">class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
val length get() = bytes.size
val length get() = bytes.size


Line 2,484: Line 2,449:
GHI£€ as a ByteString is GHI£?
GHI£€ as a ByteString is GHI£?
</pre>
</pre>

=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Liberty BASIC's strings are native byte strings. They can contain any byte sequence. They are not zero-terminated. They can be huge in size.
Liberty BASIC's strings are native byte strings. They can contain any byte sequence. They are not zero-terminated. They can be huge in size.
<syntaxhighlight lang=lb>
<syntaxhighlight lang="lb">
'string creation
'string creation
s$ = "Hello, world!"
s$ = "Hello, world!"
Line 2,522: Line 2,486:
s$ = "Good" + "bye" + " for now."
s$ = "Good" + "bye" + " for now."
</syntaxhighlight>
</syntaxhighlight>

=={{header|Lingo}}==
=={{header|Lingo}}==
<syntaxhighlight lang=Lingo>-- String creation and destruction
<syntaxhighlight lang="lingo">-- String creation and destruction
foo = "Hello world!" -- created by assignment; destruction via garbage collection
foo = "Hello world!" -- created by assignment; destruction via garbage collection


Line 2,584: Line 2,547:
foo = "Hello" & SPACE & "world!"
foo = "Hello" & SPACE & "world!"
foo = "Hello" && "world!"</syntaxhighlight>
foo = "Hello" && "world!"</syntaxhighlight>

=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>foo = 'foo' -- Ducktyping foo to be string 'foo'
<syntaxhighlight lang="lua">foo = 'foo' -- Ducktyping foo to be string 'foo'
bar = 'bar'
bar = 'bar'
assert (foo == "foo") -- Comparing string var to string literal
assert (foo == "foo") -- Comparing string var to string literal
Line 2,617: Line 2,579:


str = foo .. bar -- Strings concatenate with .. operator</syntaxhighlight>
str = foo .. bar -- Strings concatenate with .. operator</syntaxhighlight>

=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>(* String creation and destruction *) BinaryString = {}; BinaryString = . ;
<syntaxhighlight lang="mathematica">(* String creation and destruction *) BinaryString = {}; BinaryString = . ;
(* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65}
(* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65}
-> {12,56,82,65}
-> {12,56,82,65}
Line 2,638: Line 2,599:
(* Join strings *) BinaryString4 = Join[BinaryString1 , BinaryString2]
(* Join strings *) BinaryString4 = Join[BinaryString1 , BinaryString2]
-> {12,56,82,65,83,12,56,65}</syntaxhighlight>
-> {12,56,82,65,83,12,56,65}</syntaxhighlight>

=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab>
<syntaxhighlight lang="matlab">
a=['123',0,' abc '];
a=['123',0,' abc '];
b=['456',9];
b=['456',9];
Line 2,693: Line 2,653:
123 abc @456 789
123 abc @456 789
</pre>
</pre>

=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>var # creation
<syntaxhighlight lang="nim">var # creation
x = "this is a string"
x = "this is a string"
y = "this is another string"
y = "this is another string"
Line 2,718: Line 2,677:


echo z.replace('t', 'T') # replace occurences of t with T</syntaxhighlight>
echo z.replace('t', 'T') # replace occurences of t with T</syntaxhighlight>

=={{header|OCaml}}==
=={{header|OCaml}}==


Line 2,724: Line 2,682:


<code>String.create n</code> returns a fresh string of length n, which initially contains arbitrary characters:
<code>String.create n</code> returns a fresh string of length n, which initially contains arbitrary characters:
<syntaxhighlight lang=ocaml># String.create 10 ;;
<syntaxhighlight lang="ocaml"># String.create 10 ;;
- : string = "\000\023\000\000\001\000\000\000\000\000"</syntaxhighlight>
- : string = "\000\023\000\000\001\000\000\000\000\000"</syntaxhighlight>


Line 2,732: Line 2,690:


* String assignment
* String assignment
<syntaxhighlight lang=ocaml># let str = "some text" ;;
<syntaxhighlight lang="ocaml"># let str = "some text" ;;
val str : string = "some text"
val str : string = "some text"


Line 2,740: Line 2,698:


* String comparison
* String comparison
<syntaxhighlight lang=ocaml># str = "Some text" ;;
<syntaxhighlight lang="ocaml"># str = "Some text" ;;
- : bool = true
- : bool = true


Line 2,747: Line 2,705:


* String cloning and copying
* String cloning and copying
<syntaxhighlight lang=ocaml># String.copy str ;;
<syntaxhighlight lang="ocaml"># String.copy str ;;
- : string = "Some text"</syntaxhighlight>
- : string = "Some text"</syntaxhighlight>


* Check if a string is empty
* Check if a string is empty
<syntaxhighlight lang=ocaml># let string_is_empty s = (s = "") ;;
<syntaxhighlight lang="ocaml"># let string_is_empty s = (s = "") ;;
val string_is_empty : string -> bool = <fun>
val string_is_empty : string -> bool = <fun>


Line 2,767: Line 2,725:
a byte and return the result as a new string
a byte and return the result as a new string


<syntaxhighlight lang=ocaml># str ^ "!" ;;
<syntaxhighlight lang="ocaml"># str ^ "!" ;;
- : string = "Some text!"</syntaxhighlight>
- : string = "Some text!"</syntaxhighlight>


Line 2,773: Line 2,731:
This module implements string buffers that automatically expand as necessary. It provides accumulative concatenation of strings in quasi-linear time (instead of quadratic time when strings are concatenated pairwise).
This module implements string buffers that automatically expand as necessary. It provides accumulative concatenation of strings in quasi-linear time (instead of quadratic time when strings are concatenated pairwise).


<syntaxhighlight lang=ocaml>Buffer.add_char str c</syntaxhighlight>
<syntaxhighlight lang="ocaml">Buffer.add_char str c</syntaxhighlight>


* Extract a substring from a string
* Extract a substring from a string
<syntaxhighlight lang=ocaml># String.sub str 5 4 ;;
<syntaxhighlight lang="ocaml"># String.sub str 5 4 ;;
- : string = "text"</syntaxhighlight>
- : string = "text"</syntaxhighlight>


* Replace every occurrence of a byte (or a string) in a string with another string
* Replace every occurrence of a byte (or a string) in a string with another string
using the '''Str''' module
using the '''Str''' module
<syntaxhighlight lang=ocaml># #load "str.cma";;
<syntaxhighlight lang="ocaml"># #load "str.cma";;
# let replace str occ by =
# let replace str occ by =
Str.global_replace (Str.regexp_string occ) by str
Str.global_replace (Str.regexp_string occ) by str
Line 2,790: Line 2,748:


* Join strings
* Join strings
<syntaxhighlight lang=ocaml># "Now just remind me" ^ " how the horse moves again?" ;;
<syntaxhighlight lang="ocaml"># "Now just remind me" ^ " how the horse moves again?" ;;
- : string = "Now just remind me how the horse moves again?"</syntaxhighlight>
- : string = "Now just remind me how the horse moves again?"</syntaxhighlight>

=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
This code accepts arbitrary characters, but you can use <code>Strchr</code> to display ASCII strings.
This code accepts arbitrary characters, but you can use <code>Strchr</code> to display ASCII strings.
<syntaxhighlight lang=parigp>cmp_str(u,v)=u==v
<syntaxhighlight lang="parigp">cmp_str(u,v)=u==v
copy_str(v)=v \\ Creates a copy, not a pointer
copy_str(v)=v \\ Creates a copy, not a pointer
append_str(v,n)=concat(v,n)
append_str(v,n)=concat(v,n)
Line 2,817: Line 2,774:
%6 = [72, 101, 121, 121, 111, 44, 32, 119, 111, 114, 121, 100]
%6 = [72, 101, 121, 121, 111, 44, 32, 119, 111, 114, 121, 100]
%7 = []</pre>
%7 = []</pre>

=={{header|Pascal}}==
=={{header|Pascal}}==
Pascal's original strings were limited to 255 characters. Most implementations had the string length in byte 0. Extension exist for longer strings as well as C compatible string terminated by null. See Examples below
Pascal's original strings were limited to 255 characters. Most implementations had the string length in byte 0. Extension exist for longer strings as well as C compatible string terminated by null. See Examples below
<syntaxhighlight lang=pascal>const
<syntaxhighlight lang="pascal">const
greeting = 'Hello';
greeting = 'Hello';
var
var
Line 2,846: Line 2,802:
s3 := greeting + ' and how are you, ' + s1 + '?';
s3 := greeting + ' and how are you, ' + s1 + '?';
end.</syntaxhighlight>
end.</syntaxhighlight>

=={{header|Perl}}==
=={{header|Perl}}==
Effective string manipulation has been a part of Perl since the beginning. Simple stuff is simply done, but modern Perl also supports Unicode, and tools like <code>pack/unpack</code> let you operate on strings below the level of bytes.
Effective string manipulation has been a part of Perl since the beginning. Simple stuff is simply done, but modern Perl also supports Unicode, and tools like <code>pack/unpack</code> let you operate on strings below the level of bytes.
<syntaxhighlight lang=perl>$s = undef;
<syntaxhighlight lang="perl">$s = undef;
say 'Nothing to see here' if ! defined $s; # 'Nothing to see here'
say 'Nothing to see here' if ! defined $s; # 'Nothing to see here'
say $s = ''; # ''
say $s = ''; # ''
Line 2,861: Line 2,816:
say $u = substr $t, 2, 2; # 'ok'
say $u = substr $t, 2, 2; # 'ok'
say 'Oklahoma' . ' is ' . uc $u; # 'Oklahoma is OK'</syntaxhighlight>
say 'Oklahoma' . ' is ' . uc $u; # 'Oklahoma is OK'</syntaxhighlight>

=={{header|Phix}}==
=={{header|Phix}}==
The native string type in Phix can be used to store raw binary data and supports all of the operations mentioned in this task.
The native string type in Phix can be used to store raw binary data and supports all of the operations mentioned in this task.
Strings are reference counted, and mutable with copy-on-write semantics. Memory is managed automatically and very efficiently, strings can easily be a billion characters long (on 32-bit, the precise limit is in fact 1,610,612,711 characters, available memory and performance impacts aside) and have a null terminator for C compatibility, but can contain embedded nulls as well.
Strings are reference counted, and mutable with copy-on-write semantics. Memory is managed automatically and very efficiently, strings can easily be a billion characters long (on 32-bit, the precise limit is in fact 1,610,612,711 characters, available memory and performance impacts aside) and have a null terminator for C compatibility, but can contain embedded nulls as well.
Note that attempting to set an element (character/byte) to a value outside the range 0..255 will result in automatic expansion to dword-(or qword-)sequence, and can result in a run-time type check.
Note that attempting to set an element (character/byte) to a value outside the range 0..255 will result in automatic expansion to dword-(or qword-)sequence, and can result in a run-time type check.
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"abc"</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"abc"</span>
Line 2,911: Line 2,865:
"abc\ndef\nghi"
"abc\ndef\nghi"
</pre>
</pre>

=={{header|Picat}}==
=={{header|Picat}}==
Strings in Picat are lists of characters.
Strings in Picat are lists of characters.
<syntaxhighlight lang=Picat>main => % - String assignment
<syntaxhighlight lang="picat">main => % - String assignment
S1 = "binary_string",
S1 = "binary_string",
println(s1=S1),
println(s1=S1),
Line 2,988: Line 2,941:


Since strings are lists of characters, all list functions/procedures are supported including the non-deterministic (backtrackable) <code>member/2</code>, <code>append/3-4</code>, <code>select/3</code> as well as list comprehensions. Some examples:
Since strings are lists of characters, all list functions/procedures are supported including the non-deterministic (backtrackable) <code>member/2</code>, <code>append/3-4</code>, <code>select/3</code> as well as list comprehensions. Some examples:
<syntaxhighlight lang=Picat>main =>
<syntaxhighlight lang="picat">main =>
println(member=findall(C,(member(C,S1), C @< 'l') )),
println(member=findall(C,(member(C,S1), C @< 'l') )),


Line 3,012: Line 2,965:
list_comprehension = aoeiaoei
list_comprehension = aoeiaoei
sort_remove_dups = aeghinorst</pre>
sort_remove_dups = aeghinorst</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Byte strings are represented in PicoLisp as lists of numbers. They can be
Byte strings are represented in PicoLisp as lists of numbers. They can be
Line 3,020: Line 2,971:
I/O of raw bytes is done via the 'wr' (write) and 'rd' (read) functions. The
I/O of raw bytes is done via the 'wr' (write) and 'rd' (read) functions. The
following creates a file consisting of 256 bytes, with values from 0 to 255:
following creates a file consisting of 256 bytes, with values from 0 to 255:
<syntaxhighlight lang=PicoLisp>: (out "rawfile"
<syntaxhighlight lang="picolisp">: (out "rawfile"
(mapc wr (range 0 255)) )</syntaxhighlight>
(mapc wr (range 0 255)) )</syntaxhighlight>
Looking at a hex dump of that file:
Looking at a hex dump of that file:
<syntaxhighlight lang=PicoLisp>: (hd "rawfile")
<syntaxhighlight lang="picolisp">: (hd "rawfile")
00000000 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ................
00000000 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ................
00000010 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F ................
00000010 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F ................
Line 3,030: Line 2,981:
...</syntaxhighlight>
...</syntaxhighlight>
To read part of that file, an external tool like 'dd' might be used:
To read part of that file, an external tool like 'dd' might be used:
<syntaxhighlight lang=PicoLisp>: (in '(dd "skip=32" "bs=1" "count=16" "if=rawfile")
<syntaxhighlight lang="picolisp">: (in '(dd "skip=32" "bs=1" "count=16" "if=rawfile")
(make
(make
(while (rd 1)
(while (rd 1)
Line 3,041: Line 2,992:
If desired, a string containing meaningful values can also be converted to
If desired, a string containing meaningful values can also be converted to
a transient symbol, e.g. the example above
a transient symbol, e.g. the example above
<syntaxhighlight lang=PicoLisp>: (pack (mapcar char (32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47)))
<syntaxhighlight lang="picolisp">: (pack (mapcar char (32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47)))
-> " !\"#$%&'()*+,-./"</syntaxhighlight>
-> " !\"#$%&'()*+,-./"</syntaxhighlight>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=PL/I>
<syntaxhighlight lang="pl/i">
/* PL/I has immediate facilities for all those operations except for */
/* PL/I has immediate facilities for all those operations except for */
/* replace. */
/* replace. */
Line 3,069: Line 3,019:
end replace;
end replace;
</syntaxhighlight>
</syntaxhighlight>

=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
Clear-Host
Clear-Host


Line 3,200: Line 3,149:
10 11 12
10 11 12
</pre>
</pre>

=={{header|Prolog}}==
=={{header|Prolog}}==


<syntaxhighlight lang=prolog>% Create a string (no destruction necessary)
<syntaxhighlight lang="prolog">% Create a string (no destruction necessary)
?- X = "a test string".
?- X = "a test string".
X = "a test string".
X = "a test string".
Line 3,253: Line 3,201:
Z = "a test string with extra!".
Z = "a test string with extra!".
</syntaxhighlight>
</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>
<syntaxhighlight lang="purebasic">
;string creation
;string creation
x$ = "hello world"
x$ = "hello world"
Line 3,283: Line 3,230:
x$ = "hel" + "lo w" + "orld"
x$ = "hel" + "lo w" + "orld"
</syntaxhighlight>
</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
===2.x===
===2.x===
Line 3,290: Line 3,236:
* String creation
* String creation


<syntaxhighlight lang=python>s1 = "A 'string' literal \n"
<syntaxhighlight lang="python">s1 = "A 'string' literal \n"
s2 = 'You may use any of \' or " as delimiter'
s2 = 'You may use any of \' or " as delimiter'
s3 = """This text
s3 = """This text
Line 3,300: Line 3,246:
There is nothing special about assignments:
There is nothing special about assignments:


<syntaxhighlight lang=python>s = "Hello "
<syntaxhighlight lang="python">s = "Hello "
t = "world!"
t = "world!"
u = s + t # + concatenates</syntaxhighlight>
u = s + t # + concatenates</syntaxhighlight>
Line 3,308: Line 3,254:
They're compared byte by byte, lexicographically:
They're compared byte by byte, lexicographically:


<syntaxhighlight lang=python>assert "Hello" == 'Hello'
<syntaxhighlight lang="python">assert "Hello" == 'Hello'
assert '\t' == '\x09'
assert '\t' == '\x09'
assert "one" < "two"
assert "one" < "two"
Line 3,319: Line 3,265:
* Check if a string is empty
* Check if a string is empty


<syntaxhighlight lang=python>if x=='': print "Empty string"
<syntaxhighlight lang="python">if x=='': print "Empty string"
if not x: print "Empty string, provided you know x is a string"</syntaxhighlight>
if not x: print "Empty string, provided you know x is a string"</syntaxhighlight>


* Append a byte to a string
* Append a byte to a string


<syntaxhighlight lang=python>txt = "Some text"
<syntaxhighlight lang="python">txt = "Some text"
txt += '\x07'
txt += '\x07'
# txt refers now to a new string having "Some text\x07"</syntaxhighlight>
# txt refers now to a new string having "Some text\x07"</syntaxhighlight>
Line 3,332: Line 3,278:
Strings are sequences, they can be indexed with s[index] (index is 0-based) and sliced s[start:stop] (all characters from s[start] up to, but ''not'' including, s[stop])
Strings are sequences, they can be indexed with s[index] (index is 0-based) and sliced s[start:stop] (all characters from s[start] up to, but ''not'' including, s[stop])


<syntaxhighlight lang=python>txt = "Some more text"
<syntaxhighlight lang="python">txt = "Some more text"
assert txt[4] == " "
assert txt[4] == " "
assert txt[0:4] == "Some"
assert txt[0:4] == "Some"
Line 3,341: Line 3,287:
Negative indexes count from the end: -1 is the last byte, and so on:
Negative indexes count from the end: -1 is the last byte, and so on:


<syntaxhighlight lang=python>txt = "Some more text"
<syntaxhighlight lang="python">txt = "Some more text"
assert txt[-1] == "t"
assert txt[-1] == "t"
assert txt[-4:] == "text"</syntaxhighlight>
assert txt[-4:] == "text"</syntaxhighlight>
Line 3,349: Line 3,295:
Strings are objects and have methods, like replace:
Strings are objects and have methods, like replace:


<syntaxhighlight lang=python>v1 = "hello world"
<syntaxhighlight lang="python">v1 = "hello world"
v2 = v1.replace("l", "L")
v2 = v1.replace("l", "L")
print v2 # prints heLLo worLd</syntaxhighlight>
print v2 # prints heLLo worLd</syntaxhighlight>
Line 3,357: Line 3,303:
If they're separate variables, use the + operator:
If they're separate variables, use the + operator:


<syntaxhighlight lang=python>v1 = "hello"
<syntaxhighlight lang="python">v1 = "hello"
v2 = "world"
v2 = "world"
msg = v1 + " " + v2</syntaxhighlight>
msg = v1 + " " + v2</syntaxhighlight>
Line 3,363: Line 3,309:
If the elements to join are contained inside any iterable container (e.g. a list)
If the elements to join are contained inside any iterable container (e.g. a list)


<syntaxhighlight lang=python>items = ["Smith", "John", "417 Evergreen Av", "Chimichurri", "481-3172"]
<syntaxhighlight lang="python">items = ["Smith", "John", "417 Evergreen Av", "Chimichurri", "481-3172"]
joined = ",".join(items)
joined = ",".join(items)
print joined
print joined
Line 3,371: Line 3,317:
The reverse operation (split) is also possible:
The reverse operation (split) is also possible:


<syntaxhighlight lang=python>line = "Smith,John,417 Evergreen Av,Chimichurri,481-3172"
<syntaxhighlight lang="python">line = "Smith,John,417 Evergreen Av,Chimichurri,481-3172"
fields = line.split(',')
fields = line.split(',')
print fields
print fields
Line 3,381: Line 3,327:


To specify a literal immutable byte string (<code>bytes</code>), prefix a string literal with "b":
To specify a literal immutable byte string (<code>bytes</code>), prefix a string literal with "b":
<syntaxhighlight lang=python>s1 = b"A 'byte string' literal \n"
<syntaxhighlight lang="python">s1 = b"A 'byte string' literal \n"
s2 = b'You may use any of \' or " as delimiter'
s2 = b'You may use any of \' or " as delimiter'
s3 = b"""This text
s3 = b"""This text
Line 3,390: Line 3,336:


Indexing a byte string results in an integer (the byte value at that byte):
Indexing a byte string results in an integer (the byte value at that byte):
<syntaxhighlight lang=python>x = b'abc'
<syntaxhighlight lang="python">x = b'abc'
x[0] # evaluates to 97</syntaxhighlight>
x[0] # evaluates to 97</syntaxhighlight>


Similarly, a byte string can be converted to and from a list of integers:
Similarly, a byte string can be converted to and from a list of integers:


<syntaxhighlight lang=python>x = b'abc'
<syntaxhighlight lang="python">x = b'abc'
list(x) # evaluates to [97, 98, 99]
list(x) # evaluates to [97, 98, 99]
bytes([97, 98, 99]) # evaluates to b'abc'</syntaxhighlight>
bytes([97, 98, 99]) # evaluates to b'abc'</syntaxhighlight>

=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 3,450: Line 3,395:
(bytes-join (list b2 b3) #" ") ; -> #"BBBBB BAAAA"
(bytes-join (list b2 b3) #" ") ; -> #"BBBBB BAAAA"
</syntaxhighlight>
</syntaxhighlight>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang=raku line># Raku is perfectly fine with NUL *characters* in strings:
<syntaxhighlight lang="raku" line># Raku is perfectly fine with NUL *characters* in strings:
my Str $s = 'nema' ~ 0.chr ~ 'problema!';
my Str $s = 'nema' ~ 0.chr ~ 'problema!';
say $s;
say $s;
Line 3,554: Line 3,498:
replaced = [103 0 0 0 10 98 97 114 123]
replaced = [103 0 0 0 10 98 97 114 123]
joined = [103 0 0 0 10 98 97 114 123 0 0 10 98]</pre>
joined = [103 0 0 0 10 98 97 114 123 0 0 10 98]</pre>

=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang=Rebol>Red []
<syntaxhighlight lang="rebol">Red []
s: copy "abc" ;; string creation
s: copy "abc" ;; string creation


Line 3,584: Line 3,527:
>>
>>
</pre>
</pre>

=={{header|REXX}}==
=={{header|REXX}}==
Programming note: &nbsp; this REXX example demonstrates two types of &nbsp; ''quoting''.
Programming note: &nbsp; this REXX example demonstrates two types of &nbsp; ''quoting''.
<syntaxhighlight lang=REXX>/*REXX program demonstrates methods (code examples) to use and express binary strings.*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates methods (code examples) to use and express binary strings.*/
dingsta= '11110101'b /*four versions, bit string assignment.*/
dingsta= '11110101'b /*four versions, bit string assignment.*/
dingsta= "11110101"b /*this is the same assignment as above.*/
dingsta= "11110101"b /*this is the same assignment as above.*/
Line 3,608: Line 3,550:
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
<br><br>

=={{header|Ring}}==
=={{header|Ring}}==
The String in the Ring programming language holds and manipulates an arbitrary sequence of bytes.
The String in the Ring programming language holds and manipulates an arbitrary sequence of bytes.


<syntaxhighlight lang=ring># string creation
<syntaxhighlight lang="ring"># string creation
x = "hello world"
x = "hello world"
Line 3,656: Line 3,597:
See a + b + c
See a + b + c
</syntaxhighlight>
</syntaxhighlight>

=={{header|Ruby}}==
=={{header|Ruby}}==
A String object holds and manipulates an arbitrary sequence of bytes. There are also the [http://www.ruby-doc.org/core/classes/Array.html#M002222 Array#pack] and [http://www.ruby-doc.org/core/classes/String.html#M000760 String#unpack] methods to convert data to binary strings.
A String object holds and manipulates an arbitrary sequence of bytes. There are also the [http://www.ruby-doc.org/core/classes/Array.html#M002222 Array#pack] and [http://www.ruby-doc.org/core/classes/String.html#M000760 String#unpack] methods to convert data to binary strings.
<syntaxhighlight lang=ruby># string creation
<syntaxhighlight lang="ruby"># string creation
x = "hello world"
x = "hello world"
Line 3,706: Line 3,646:
c = "orld"
c = "orld"
p d = a + b + c</syntaxhighlight>
p d = a + b + c</syntaxhighlight>

=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<syntaxhighlight lang=runbasic>' Create string
<syntaxhighlight lang="runbasic">' Create string
s$ = "Hello, world"
s$ = "Hello, world"
Line 3,741: Line 3,680:
s$ = "See " + "you " + "later."
s$ = "See " + "you " + "later."
print s$</syntaxhighlight>
print s$</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==
For extra documentation, refer to [https://doc.rust-lang.org/std/string/struct.String.html] and [https://doc.rust-lang.org/book/strings.html].
For extra documentation, refer to [https://doc.rust-lang.org/std/string/struct.String.html] and [https://doc.rust-lang.org/book/strings.html].
<syntaxhighlight lang=rust>use std::str;
<syntaxhighlight lang="rust">use std::str;


fn main() {
fn main() {
Line 3,815: Line 3,753:
assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split");
assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split");
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Seed7}}==
=={{header|Seed7}}==
Seed7 strings are capable to hold binary data.
Seed7 strings are capable to hold binary data.
Line 3,877: Line 3,814:
The [http://seed7.sourceforge.net/libraries/string.htm string.s7i] library contains
The [http://seed7.sourceforge.net/libraries/string.htm string.s7i] library contains
more string functions.
more string functions.

=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Smalltalk strings are variable length and unrestricted. They are builtin and no additional library is req'd.
Smalltalk strings are variable length and unrestricted. They are builtin and no additional library is req'd.


<syntaxhighlight lang=Smalltalk>s := "abc" # create a string (immutable if its a literal constant in the program)
<syntaxhighlight lang="smalltalk">s := "abc" # create a string (immutable if its a literal constant in the program)
s := #[16r01 16r02 16r00 16r03] asString # strings can contain any value, even nulls
s := #[16r01 16r02 16r00 16r03] asString # strings can contain any value, even nulls
s := String new:3. # a mutable string
s := String new:3. # a mutable string
Line 3,904: Line 3,840:


In addition (because they inherit from collection), a lot more is inherited (map, fold, enumeration, finding substrings, etc.)
In addition (because they inherit from collection), a lot more is inherited (map, fold, enumeration, finding substrings, etc.)

=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl strings are binary safe, and a binary string is any string that only contains UNICODE characters in the range <tt>\u0000</tt>–<tt>\u00FF</tt>.
Tcl strings are binary safe, and a binary string is any string that only contains UNICODE characters in the range <tt>\u0000</tt>–<tt>\u00FF</tt>.
<syntaxhighlight lang=tcl># string creation
<syntaxhighlight lang="tcl"># string creation
set x "hello world"
set x "hello world"


Line 3,943: Line 3,878:
set c "orld"
set c "orld"
set d $a$b$c</syntaxhighlight>
set d $a$b$c</syntaxhighlight>

=={{header|VBA}}==
=={{header|VBA}}==
Before start, see this link :
Before start, see this link :
Line 3,950: Line 3,884:
The default text comparison method is Binary.
The default text comparison method is Binary.
</pre>
</pre>
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
'Set the string comparison method to Binary.
'Set the string comparison method to Binary.
Option Compare Binary ' That is, "AAA" is less than "aaa".
Option Compare Binary ' That is, "AAA" is less than "aaa".
Line 3,956: Line 3,890:
Option Compare Text ' That is, "AAA" is equal to "aaa".</syntaxhighlight>
Option Compare Text ' That is, "AAA" is equal to "aaa".</syntaxhighlight>
String creation and destruction :
String creation and destruction :
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Sub Creation_String_FirstWay()
Sub Creation_String_FirstWay()
Dim myString As String
Dim myString As String
Line 3,963: Line 3,897:
End Sub '==> Here the string is destructed !</syntaxhighlight>
End Sub '==> Here the string is destructed !</syntaxhighlight>
String assignment :
String assignment :
<syntaxhighlight lang=vb>Sub String_Assignment()
<syntaxhighlight lang="vb">Sub String_Assignment()
Dim myString$
Dim myString$
'Here, myString is created and equal ""
'Here, myString is created and equal ""
Line 3,973: Line 3,907:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
String comparison :
String comparison :
<syntaxhighlight lang=vb>Sub String_Comparison_FirstWay()
<syntaxhighlight lang="vb">Sub String_Comparison_FirstWay()
Dim A$, B$, C$
Dim A$, B$, C$


Line 4,002: Line 3,936:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
String cloning and copying :
String cloning and copying :
<syntaxhighlight lang=vb>Sub String_Clone_Copy()
<syntaxhighlight lang="vb">Sub String_Clone_Copy()
Dim A As String, B$
Dim A As String, B$
A = "Hello world!"
A = "Hello world!"
Line 4,009: Line 3,943:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
Check if a string is empty :
Check if a string is empty :
<syntaxhighlight lang=vb>Sub Check_Is_Empty()
<syntaxhighlight lang="vb">Sub Check_Is_Empty()
Dim A As String, B As Variant
Dim A As String, B As Variant


Line 4,033: Line 3,967:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
Append a byte to a string :
Append a byte to a string :
<syntaxhighlight lang=vb>Sub Append_to_string()
<syntaxhighlight lang="vb">Sub Append_to_string()
Dim A As String
Dim A As String
A = "Hello worl"
A = "Hello worl"
Line 4,039: Line 3,973:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
Extract a substring from a string :
Extract a substring from a string :
<syntaxhighlight lang=vb>Sub ExtractFromString()
<syntaxhighlight lang="vb">Sub ExtractFromString()
Dim A$, B As String
Dim A$, B As String
A = "Hello world"
A = "Hello world"
Line 4,046: Line 3,980:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
Replace every occurrence of a byte (or a string) in a string with another string :
Replace every occurrence of a byte (or a string) in a string with another string :
<syntaxhighlight lang=vb>Sub ReplaceInString()
<syntaxhighlight lang="vb">Sub ReplaceInString()
Dim A$, B As String, C$
Dim A$, B As String, C$
A = "Hello world"
A = "Hello world"
Line 4,054: Line 3,988:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
Join Strings :
Join Strings :
<syntaxhighlight lang=vb>Sub Join_Strings()
<syntaxhighlight lang="vb">Sub Join_Strings()
Dim A$, B As String
Dim A$, B As String


Line 4,064: Line 3,998:
End Sub
End Sub
</syntaxhighlight>
</syntaxhighlight>

=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang=vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Sub Main()
Sub Main()
Line 4,133: Line 4,066:


End Module</syntaxhighlight>
End Module</syntaxhighlight>

=={{header|Wren}}==
=={{header|Wren}}==
In Wren, a string is simply an array of bytes. Although they are typically characters stored in UTF-8 format, they don't have to be interpreted in that way and, in recognition of this as well as for efficiency reasons, many of the built-in string functions operate at the byte level.
In Wren, a string is simply an array of bytes. Although they are typically characters stored in UTF-8 format, they don't have to be interpreted in that way and, in recognition of this as well as for efficiency reasons, many of the built-in string functions operate at the byte level.
Line 4,146: Line 4,078:


Setting a string variable to the special value ''null'' means that the variable currently has no value though it can still be assigned one later.
Setting a string variable to the special value ''null'' means that the variable currently has no value though it can still be assigned one later.
<syntaxhighlight lang=ecmascript>// create string
<syntaxhighlight lang="ecmascript">// create string
var s = "abc"
var s = "abc"


Line 4,181: Line 4,113:
t = "def"
t = "def"
var u = s + t // "abcdef"</syntaxhighlight>
var u = s + t // "abcdef"</syntaxhighlight>

=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic>// Rosetta Code problem: http://rosettacode.org/wiki/Binary_strings
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Binary_strings
// by Galileo, 07/2022
// by Galileo, 07/2022


Line 4,224: Line 4,155:
See you later.
See you later.
---Program done, press RETURN---</pre>
---Program done, press RETURN---</pre>

=={{header|zkl}}==
=={{header|zkl}}==
Strings in zkl are bytes with a zero terminator. So they are binary safe as long as the data doesn't contain a zero. Data objects are true binary strings: bytes with a length. It is basically a binary editor. Datas come in two flavors: Int and String. The difference is some methods treat String type as containing (zero or more) null terminated strings. Datas have an implicit null terminator so they can easily convert to a String.
Strings in zkl are bytes with a zero terminator. So they are binary safe as long as the data doesn't contain a zero. Data objects are true binary strings: bytes with a length. It is basically a binary editor. Datas come in two flavors: Int and String. The difference is some methods treat String type as containing (zero or more) null terminated strings. Datas have an implicit null terminator so they can easily convert to a String.
<syntaxhighlight lang=zkl>Data(0,.Int,1,2,3) // bytes
<syntaxhighlight lang="zkl">Data(0,.Int,1,2,3) // bytes
Data(0,String,1,2,3) // same
Data(0,String,1,2,3) // same
Data(0,Int,"foo","bar") //-->foobar\0
Data(0,Int,"foo","bar") //-->foobar\0
Line 4,248: Line 4,178:
d2:=Data(0,Int,"sam");
d2:=Data(0,Int,"sam");
d.append(d2).text // or d+d2</syntaxhighlight>
d.append(d2).text // or d+d2</syntaxhighlight>

{{omit from|GUISS}}
{{omit from|GUISS}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Lotus 123 Macro Scripting}}