Binary strings: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
(20 intermediate revisions by 11 users not shown)
Line 21:
Possible contexts of use: compression algorithms (like [[LZW compression]]), L-systems (manipulation of symbols), many more.
<br><br>
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V x = Bytes(‘abc’)
print(x[0])</langsyntaxhighlight>
 
{{out}}
Line 30 ⟶ 29:
97
</pre>
 
=={{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.)
 
===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.
<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
mov si,offset TestMessage
Line 44 ⟶ 43:
ret
 
;there is no buffer overflow protection built into these functions so be careful!
;be careful!!!
TestMessage byte "Hello"
EmptyRam byte 0,0,0,0,0</langsyntaxhighlight>
 
===Checking if a particular byte exists===
<langsyntaxhighlight lang="asm">;this code assumes that ES points to the correct segment.
cld
mov di,offset TestMessage
Line 60 ⟶ 58:
ret
 
TestMessage byte "Hello"</langsyntaxhighlight>
 
===Compare two strings===
<langsyntaxhighlight lang="asm">;this code assumes that both DS and ES point to the correct segments.
cld
mov si,offset foo
Line 76 ⟶ 74:
 
foo byte "test"
bar byte "test"</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight Adalang="ada">declare
Data : Storage_Array (1..20); -- Data created
begin
Line 97 ⟶ 94:
... Data & (1,2,3,4) ... -- The result is Data with bytes 1,2,3,4 appended
... Data (3..5) ... -- The result the substring of Data from 3 to 5
end; -- Data destructed</langsyntaxhighlight>
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:
<langsyntaxhighlight Adalang="ada">type Octet is mod 2**8;
for Octet'Size use 8;
type Octet_String is array (Positive range <>) of Octet;</langsyntaxhighlight>
Alternatively:
<langsyntaxhighlight Adalang="ada">with Interfaces; use Interfaces;
...
type Octet is new Interfaces.Unsigned_8;
type Octet_String is array (Positive range <>) of Octet;</langsyntaxhighlight>
Note that all of these types will have all operations described above.
 
=={{header|ALGOL 68}}==
{{trans|Tcl}}
Line 115 ⟶ 111:
{{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}} -->
<langsyntaxhighlight lang="algol68"># String creation #
STRING a,b,c,d,e,f,g,h,i,j,l,r;
a := "hello world";
Line 207 ⟶ 203:
 
# Extract a CHAR from a CPU word #
print(("7th byte in CPU word is: ", offset ELEM word, new line))</langsyntaxhighlight>
Output:
<pre>
Line 229 ⟶ 225:
7th byte in CPU word is: w
</pre>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">; creation
x: "this is a string"
y: "this is another string"
Line 266 ⟶ 261:
 
; replace occurrences of substring
print replace z "t" "T"</langsyntaxhighlight>
 
{{out}}
Line 276 ⟶ 271:
this is a string!now this is another string too
This is a sTring!now This is anoTher sTring Too</pre>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 314 ⟶ 308:
d=a""b""c;
printf("d=<%s>\n",d);
}</langsyntaxhighlight>
 
Output:
Line 325 ⟶ 319:
d=<123 abc @456 789>
</pre>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM)
A$ = "STRING" : REM CREATION
A$ = "" : REM DESTRUCTION
Line 356 ⟶ 349:
 
REM JOIN STRINGS
J$ = A$ + STR$(42) + " PUDDLES " + B$ + CHR$(255) : REM USE +</langsyntaxhighlight>
 
==={{header|GW-BASIC}}===
Also works in QBASIC, QuickBASIC, VB-DOS and PDS 7.1
<syntaxhighlight lang="qbasic">
<lang QBASIC>
10 ' SAVE"BINSTR", A
20 ' This program does string manipulation
Line 373 ⟶ 366:
110 B$ = "e": WHILE INSTR(A$, B$) > 0: MID$(A$, INSTR(A$, B$), 1) = "x": WEND: PRINT A$' Replace every ocurrence of a byte in a string with another string
120 C$ = A$ + " and " + STRING$(10, "-"): PRINT C$' Join strings
130 END</langsyntaxhighlight>
 
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 RANDOMIZE
110 REM create two strings
120 LET S$="Hello":LET T$="Bob"
Line 389 ⟶ 382:
200 IF S$=T$ THEN PRINT "Strings are the same."
210 REM print characters 2 to 4 of a string (a substring)
220 PRINT S$(2:4)</langsyntaxhighlight>
 
==={{header|OxygenBasic}}===
<syntaxhighlight lang="text">
'STRING CREATION AND DESTRUCTION
string A
A = "STRING" 'CREATION
A = "" 'EMPTY
del A 'DESTRUCTION
'STRING ASSIGNMENT
string A = "STRING"
string R = "DEUX"
 
'STRING COMPARISON
print A==R : print A<>R ': print A<=R : print A>=R : print A<R : print A>R
'STRING CLONING AND COPYING
string B = A
'CHECK IF A STRING IS EMPTY
if not A then print "A is empty"
'APPEND A BYTE TO A STRING
A = A + chr(0)
A += chr(0)
'EXTRACT A SUBSTRING FROM A STRING
string S = mid(A, 2, 3)
'REPLACE EVERY OCCURRENCE OF A STRING) IN A STRING WITH ANOTHER STRING
int I=1
do
I=instr(I,S,"abc")
if not I
exit do
endif
S=left(S,I-1)+"defg"+mid(S,I+3)
I+=4
loop
'JOIN STRINGS
A="DUCKS "
string J = A str(42) " PUDDLES " R chr(255) 'CAN ALSO USE '+' OR '&' BTWEEN STRINGS
print J
</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
<langsyntaxhighlight lang="basic">10 REM create two strings
20 LET s$ = "Hello"
30 LET t$ = "Bob"
Line 404 ⟶ 442:
110 IF s$ = t$ THEN PRINT "Strings are the same"
120 REM print characters 2 to 4 of a string (a substring)
130 PRINT s$(2 TO 4)</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> A$ = CHR$(0) + CHR$(1) + CHR$(254) + CHR$(255) : REM assignment
B$ = A$ : REM clone / copy
IF A$ = B$ THEN PRINT "Strings are equal" : REM comparison
Line 422 ⟶ 459:
IF I% MID$(A$, I%, 1) = new$
UNTIL I% = 0
</syntaxhighlight>
</lang>
 
 
=={{header|BQN}}==
 
Line 432 ⟶ 467:
 
* Example binary string creation
<langsyntaxhighlight lang="bqn"> name ← ""</langsyntaxhighlight>
 
* Example binary string deletion: effectively replaces the data with an integer, removing it from an accessible name.
<syntaxhighlight lang ="bqn"> name ↩ 0</langsyntaxhighlight>
 
* Example binary string assignment
<langsyntaxhighlight lang="bqn"> name ← "value"</langsyntaxhighlight>
 
* Example binary string comparison
<syntaxhighlight lang ="bqn"> name1 ≡ name2</langsyntaxhighlight>
 
* Example binary string cloning and copying
<langsyntaxhighlight lang="bqn"> name1 ← "example"
name2 ← name1</langsyntaxhighlight>
 
* Example check if a binary string is empty
<langsyntaxhighlight lang="bqn"> 0=≠string</langsyntaxhighlight>
 
* Example apppend a byte to a binary string
<langsyntaxhighlight lang="bqn"> string ← "example"
byte ← @
string ∾↩ byte</langsyntaxhighlight>
 
* Extract a substring from a binary string
<langsyntaxhighlight lang="bqn"> 3↓¯5↓"The quick brown fox runs..."</langsyntaxhighlight>
 
* Join strings
<langsyntaxhighlight lang="bqn"> "string1"∾"string2"</langsyntaxhighlight>
 
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 + @</langsyntaxhighlight>
 
Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
<syntaxhighlight lang ="bqn">1‿0‿255 + @</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 605 ⟶ 639:
 
return 0;
}</langsyntaxhighlight>
=={{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++}}==
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 671 ⟶ 772:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>ab
Line 684 ⟶ 785:
hello
hello world</pre>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|3.0}}
 
<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);
}
}</lang>
 
=={{header|Common Lisp}}==
String creation (garbage collection will handle its destruction)
using the string as an atom and casting a character list to a string
<langsyntaxhighlight lang="lisp">
"string"
(coerce '(#\s #\t #\r #\i #\n #\g) 'string)
</syntaxhighlight>
</lang>
 
String assignment
<langsyntaxhighlight lang="lisp">
(defvar *string* "string")
</syntaxhighlight>
</lang>
 
comparing two string
<langsyntaxhighlight lang="lisp">
(equal "string" "string")
</syntaxhighlight>
</lang>
 
copy a string
<langsyntaxhighlight lang="lisp">
(copy-seq "string")
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="lisp">
(defun string-empty-p (string)
(zerop (length string)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">
(concatenate 'string "string" "b")
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="lisp">
(subseq "string" 12 6)
"ring"
</syntaxhighlight>
</lang>
 
string replacement isn't covered by the ansi standard probably best to use (replace-all) or cl-ppcre
Line 794 ⟶ 825:
 
joining strings works in the same way as appending bytes
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE NpctBinaryString;
IMPORT StdLog,Strings;
Line 862 ⟶ 892:
END Do;
END NpctBinaryString.
</syntaxhighlight>
</lang>
Execute: ^Q NpctBinaryString.Do<br/>
Output:
Line 877 ⟶ 907:
pStr + '.' + pAux:>First string.Second String
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() /*@safe*/ {
import std.array: empty, replace;
import std.string: representation, assumeUTF;
Line 923 ⟶ 952:
// Join two strings.
ubyte[] str3 = str1 ~ str2;
}</langsyntaxhighlight>
 
=={{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.
 
<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"
</lang>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Binary_strings;
 
Line 1,017 ⟶ 1,030:
 
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>ab
Line 1,031 ⟶ 1,044:
hello
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}}==
 
Line 1,040 ⟶ 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).
 
<langsyntaxhighlight lang="e">? def int8 := <type:java.lang.Byte>
# value: int8</langsyntaxhighlight>
 
<ol>
<li>There are several ways to create a FlexList; perhaps the simplest is:
<langsyntaxhighlight lang="e">? def bstr := [].diverge(int8)
# value: [].diverge()
 
Line 1,052 ⟶ 1,079:
 
? def bstr2 := [-0x7F,0x2,0x3].diverge(int8)
# value: [-127, 2, 3].diverge()</langsyntaxhighlight>
As E is a memory-safe garbage-collected language there is no explicit destruction. It is good practice to work with immutable ConstLists when reasonable, however; especially when passing strings around.
</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.
<langsyntaxhighlight lang="e">? bstr1.snapshot() < bstr2.snapshot()
# value: false</langsyntaxhighlight>
</li><li>To make an independent copy of a FlexList, simply <code>.diverge()</code> it again.
</li><li><langsyntaxhighlight lang="e">? bstr1.size().isZero()
# value: false
 
? bstr.size().isZero()
# value: true</langsyntaxhighlight>
</li><li>Appending a single element to a FlexList is done by <code>.push(<var>x</var>)</code>:
<langsyntaxhighlight lang="e">? bstr.push(0)
? bstr
# value: [0].diverge()</langsyntaxhighlight>
</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>.
<langsyntaxhighlight lang="e">? bstr1(1, 2)
# value: [2]
 
? bstr.replace(0, bstr.size(), bstr2, 1, 3)
? bstr
# value: [2, 3].diverge()</langsyntaxhighlight>
</li><li>Replacing must be written as an explicit loop; there is no built-in operation (though there is for character strings).
<langsyntaxhighlight lang="e">? for i => byte ? (byte == 2) in bstr2 { bstr2[i] := -1 }
? bstr2
# value: [-127, -1, 3].diverge()</langsyntaxhighlight>
</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.
<langsyntaxhighlight lang="e">? bstr1.append(bstr2)
? bstr1
# value: [1, 2, 3, -127, 2, 3].diverge()</langsyntaxhighlight>
</li></ol>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BinaryStrings {
@Inject Console console;
void run() {
Byte[] mutableBytes = new Byte[]; // growable and mutable string of bytes
Byte[] fixedLength = new Byte[10]; // fixed length string of bytes (all default to 0)
Byte[] literal = [0, 1, 7, 0xff]; // a "constant" string of bytes
console.print($|String creation and assignment:
| mutableBytes={mutableBytes}
| fixedLength={fixedLength}
| literal={literal}
|
);
 
console.print($|Check if a string is empty:
| mutableBytes.empty={mutableBytes.empty}
| fixedLength.empty={fixedLength.empty}
| literal.empty={literal.empty}
|
);
 
mutableBytes += 0; // add a byte (using an operator)
mutableBytes.add(1); // add a byte (using the underlying method)
mutableBytes.addAll(#07FF); // add multiple bytes (using the underlying method)
console.print($|Append a byte to a string:
| mutableBytes={mutableBytes}
|
);
 
console.print($|String comparison:
| mutableBytes==literal = {mutableBytes==literal}
| fixedLength==literal = {fixedLength==literal}
|
);
 
fixedLength = new Byte[4](i -> literal[i]); // create/copy from literal to fixedLength
val clone = fixedLength.duplicate(); // clone the array
console.print($|String cloning and copying:
| fixedLength={fixedLength}
| clone={clone}
|
);
 
console.print($|Extract a substring from a string:
| mutableBytes[1..2]={mutableBytes[1..2]}
| fixedLength[0..2]={fixedLength[0..2]}
| literal[2..3]={literal[2..3]}
|
);
 
for (Int start = 0; Int index := fixedLength.indexOf(0x01, start); start = index) {
fixedLength[index] = 0x04;
}
console.print($|Replace every occurrence of a byte in a string with another string:
| fixedLength={fixedLength}
|
);
 
for (Int start = 0; Int index := mutableBytes.indexOf(#0107, start); start = index) {
mutableBytes.replaceAll(index, #9876);
}
console.print($|Replace every occurrence of a string in a string with another string:
| mutableBytes={mutableBytes}
|
);
 
console.print($|Join strings:
| mutableBytes+fixedLength+literal={mutableBytes+fixedLength+literal}
|
);
}
}
</syntaxhighlight>
 
{{out}}
<pre>
String creation and assignment:
mutableBytes=0x
fixedLength=0x00000000000000000000
literal=0x000107FF
 
Check if a string is empty:
mutableBytes.empty=True
fixedLength.empty=False
literal.empty=False
 
Append a byte to a string:
mutableBytes=0x000107FF
 
String comparison:
mutableBytes==literal = True
fixedLength==literal = False
 
String cloning and copying:
fixedLength=0x000107FF
clone=0x000107FF
 
Extract a substring from a string:
mutableBytes[1..2]=0x0107
fixedLength[0..2]=0x000107
literal[2..3]=0x07FF
 
Replace every occurrence of a byte in a string with another string:
fixedLength=0x000407FF
 
Replace every occurrence of a string in a string with another string:
mutableBytes=0x009876FF
 
Join strings:
mutableBytes+fixedLength+literal=0x009876FF000407FF000107FF
</pre>
 
=={{header|Elixir}}==
Note: Elixir data types are immutable.
<langsyntaxhighlight lang="elixir"># String creation
x = "hello world"
 
Line 1,141 ⟶ 1,281:
b = "lo w"
c = "orld"
IO.puts a <> b <> c #=> hello world</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(binary_string).
-compile([export_all]).
 
Line 1,192 ⟶ 1,331:
replace(Rest,Value,Replacement,<< Acc/binary, Replacement >>);
replace(<<Keep,Rest/binary>>,Value,Replacement,Acc) ->
replace(Rest,Value,Replacement,<< Acc/binary, Keep >>).</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="erlang">215> binary_string:test().
Creation: <<0,1,1,2,3,5,8,13>>
Copy: <<0,1,1,2,3,5,8,13>>
Line 1,203 ⟶ 1,342:
Replacement: <<0,42,42,2,3,5,8,13>>
Append: <<0,1,1,2,3,5,8,13,21>>
Join: <<0,1,1,2,3,5,8,13,21,34,55>></langsyntaxhighlight>
 
=={{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.
 
To convert a string to a byte-array:
<langsyntaxhighlight lang="factor">"Hello, byte-array!" utf8 encode .</langsyntaxhighlight>
<pre>
B{
Line 1,216 ⟶ 1,354:
</pre>
Reverse:
<langsyntaxhighlight lang="factor">B{ 147 250 150 123 } shift-jis decode .</langsyntaxhighlight>
<pre>"日本"</pre>
 
=={{header|Forth}}==
In Forth, as in Assembler, all strings are binary ie: they are simply bytes in memory. <br>
Line 1,228 ⟶ 1,365:
 
<langsyntaxhighlight 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
 
Line 1,325 ⟶ 1,462:
comparestr 1 = ;
 
</syntaxhighlight>
</lang>
 
With the above code compiled into our system, we can test interactively
at the Forth console to see if we have satisfied the Rosetta code requirements
 
<langsyntaxhighlight 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)
Line 1,456 ⟶ 1,593:
ok
 
</syntaxhighlight>
</lang>
 
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Dim As String cad, cad2
'creación de cadenas
Line 1,500 ⟶ 1,635:
Next i
Sleep
</syntaxhighlight>
</lang>
 
 
 
 
=={{header|FutureBasic}}==
FB offers 255-character Pascal strings, and CFStrings — Apple's Core Foundation strings which are toll-free bridged with Objective-C's NSStrings.
Pascal strings are an array of bytes with the string length stored in byte 0.
CFStrings are immutable objects that encode a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of 16-bit platform-endian values, with index values starting at 0. The private contents of the string object are accessed via a pointer to its address. CFStrings are technically unlimited in length. While basic CFString manipulation is shown below, FB's CocoaUI offers a host of sophisticated accessor functions. Immutable CFStrings have a mutable sister, CFMutableStrings.
 
'''Pascal String example:'''
<syntaxhighlight lang="futurebasic">
// Pascal Strings (limited to 255 characters)
print "----------------------"
print "Pascal String Examples"
print "----------------------"
 
// Dimension strings and iterator
Str255 s, a
short i
 
// Create string
s = "Hello, world!"
 
// Get length of string using length byte at 0 index
print @"Length of \"Hello, world!\" is "; s[0]; @" characters."
 
// String destruction
s = ""
 
// String comparison
if s == "Hello, world!" then print "Strings are equal"
 
// Copying string
a = s
 
// Check If empty
if s == "" then print "String is empty"
 
// Append a byte
s = s + chr$(65)
 
// Extract a substring
a = mid$( s, 1, 5 ) // bytes 1 -> 5
 
// Substitute string "world" with "universe"
a = "Hello, world!"
for i = 1 to len$(a)
if ( mid$( a, i, 5 ) == "world" )
a = left$( a, i -1 ) + "universe" + mid$( a, i + 5 )
end if
next
print a
 
// Join strings
s = "See " + "you " + "later."
print s
print : print
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
----------------------
Pascal String Examples
----------------------
Length of "Hello, world!" is 13 characters.
String is empty
Hello, universe!
See you later.
</pre>
 
'''CFSString example:'''
<syntaxhighlight lang="futurebasic">
print @"----------------------"
print @" CFString Examples"
print @"----------------------"
 
// Dimension strings and iterator
CFStringRef c, b
NSUInteger j
 
// Create CFString as pointer to Core Foundation object
c = @"Hello, world!"
 
// Get length of string
print @"Length of \"Hello, world!\" is "; len(c); @" characters."
 
// String destruction
c = @""
 
// String comparison
if fn StringIsEqual( c, @"Hello, world!" ) then print @"Strings are equal"
 
// Copying string
b = c
 
// Check if empty
if len(c) == 0 then print @"String is empty"
 
// Append a byte
c = fn StringWithString( @"A" )
 
// Extract a substring
b = mid( c, 1, 5 )
 
// Substitute string "world" with "universe"
b = @"Hello, world!"
for j = 0 to len(b) - 1
if ( fn StringIsEqual( mid( b, j, 6 ), @"world!" ) )
b = fn StringWithFormat( @"%@%@", left( b, j ), @"universe!" )
exit for
end if
next
print b
 
// Join strings
c = fn StringWithFormat( @"%@%@%@", @"See ", @"you ", @"later." )
print c
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
----------------------
CFString Examples
----------------------
Length of "Hello, world!" is 13 characters.
String is empty
Hello, universe!
See you later.
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,588 ⟶ 1,853:
rem := append(append([]byte{}, b[:1]...), b[3:]...)
fmt.Println(string(rem))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,602 ⟶ 1,867:
bary
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.nio.charset.StandardCharsets
 
class MutableByteString {
Line 1,723 ⟶ 1,987:
return index
}
}</langsyntaxhighlight>
 
Test Code
<langsyntaxhighlight lang="groovy">import org.testng.Assert
import org.testng.annotations.Test
 
Line 1,784 ⟶ 2,048:
Assert.assertFalse(str.regionEquals(0, new MutableByteString(['h' as char] as byte[]), 0, 2))
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Note that any of the following functions can be assigned
Line 1,797 ⟶ 2,060:
as Haskell can be somewhat intimidating to the (currently) non-
functional programmer.
<langsyntaxhighlight lang="haskell">import Text.Regex
{- The above import is needed only for the last function.
It is used there purely for readability and conciseness -}
Line 1,805 ⟶ 2,068:
Haskell would be able to figure out the type
of "world" -}
string = "world" :: String</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">{- Comparing two given strings and
returning a boolean result using a
simple conditional -}
Line 1,814 ⟶ 2,077:
if x == y
then True
else False</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">{- As strings are equivalent to lists
of characters in Haskell, test and
see if the given string is an empty list -}
Line 1,823 ⟶ 2,086:
if x == []
then True
else False</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">{- This is the most obvious way to
append strings, using the built-in
(++) concatenation operator
Line 1,832 ⟶ 2,095:
as typed strings -}
strAppend :: String -> String -> String
strAppend x y = x ++ y</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">{- Take the specified number of characters
from the given string -}
strExtract :: Int -> String -> String
strExtract x s = take x s</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">{- Take a certain substring, specified by
two integers, from the given string -}
strPull :: Int -> Int -> String -> String
strPull x y s = take (y-x+1) (drop x s)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">{- Much thanks to brool.com for this nice
and elegant solution. Using an imported standard library
(Text.Regex), replace a given substring with another -}
strReplace :: String -> String -> String -> String
strReplace old new orig = subRegex (mkRegex old) orig new</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Iconlang="icon">s := "\x00" # strings can contain any value, even nulls
s := "abc" # create a string
s := &null # destroy a string (garbage collect value of s; set new value to &null)
Line 1,865 ⟶ 2,127:
t := s[2+:3] # t is set to position 2 for 3 characters
s := replace(s,s2,s3) # IPL replace function
s := s1 || s2 # concatenation (joining) of strings</langsyntaxhighlight>
 
The {{libheader|Icon Programming Library}} provides the procedure [http://www.cs.arizona.edu/icon/library/src/procs/strings.icn replace in strings]
<langsyntaxhighlight Iconlang="icon">procedure replace(s1, s2, s3) #: string replacement
local result, i
 
Line 1,883 ⟶ 2,145:
}
 
end</langsyntaxhighlight>
 
=={{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).
 
* Example binary string creation
<langsyntaxhighlight lang="j"> name=: ''</langsyntaxhighlight>
 
* 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):
<langsyntaxhighlight lang="j"> name=: 0</langsyntaxhighlight>
 
* Example binary string assignment
<langsyntaxhighlight lang="j"> name=: 'value'</langsyntaxhighlight>
 
* Example binary string comparison
<syntaxhighlight lang ="j"> name1 -: name2</langsyntaxhighlight>
 
* Example binary string cloning and copying
<langsyntaxhighlight lang="j"> name1=: 'example'
name2=: name1</langsyntaxhighlight>
 
Though, technically, its the internal reference which is cloned, not the internal representation of the value. But operations which modify strings are copy on write, so this distinction is not visible without going outside the language.
 
* Example check if a binary string is empty
<langsyntaxhighlight lang="j"> 0=#string</langsyntaxhighlight>
 
* Example apppend a byte to a binary string
<langsyntaxhighlight lang="j"> string=: 'example'
byte=: DEL
string=: string,byte</langsyntaxhighlight>
 
* Extract a substring from a binary string
<langsyntaxhighlight lang="j"> 3{.5}.'The quick brown fox runs...'</langsyntaxhighlight>
 
* Replace every occurrence of a byte (or a string) in a string with another string
<langsyntaxhighlight lang="j">require 'strings'
'The quick brown fox runs...' rplc ' ';' !!! '</langsyntaxhighlight>
 
* Join strings
<syntaxhighlight lang ="j"> 'string1','string2'</langsyntaxhighlight>
 
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.</langsyntaxhighlight>
 
Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
<syntaxhighlight lang ="j">1 0 255{a.</langsyntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java">import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
Line 2,049 ⟶ 2,309:
return index;
}
}</langsyntaxhighlight>
 
Test code:
 
<langsyntaxhighlight lang="java">import static org.hamcrest.CoreMatchers.is;
 
import java.nio.charset.StandardCharsets;
Line 2,112 ⟶ 2,372:
Assert.assertThat(str.regionEquals(0, new MutableByteString(new byte[]{'h'}), 0, 2), is(false));
}
}</langsyntaxhighlight>
 
=={{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
<langsyntaxhighlight JavaScriptlang="javascript">//String creation
var str='';
//or
Line 2,170 ⟶ 2,429:
[str," ",str3].join(" "/*this is the character that will glue the strings*/)//we can join an array of strings
str3+str4;
str.concat('\n',str4); //concantenate them</langsyntaxhighlight>
 
=={{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.
 
It is appropriate therefore to introduce a filter for verifying that an entity is an array of integers in the appropriate range:<langsyntaxhighlight lang="jq"># If the input is a valid representation of a binary string
# then pass it along:
def check_binary:
Line 2,185 ⟶ 2,443:
and 0 <= . and . <= 255) then $a
else error("\(.) is an invalid representation of a byte")
end );</langsyntaxhighlight>
Examples
<langsyntaxhighlight lang="jq">## Creation of an entity representing an empty binary string
 
[]
Line 2,257 ⟶ 2,515:
reduce .[] as $byte ([];
if $byte == x then . + a else . + [$byte] end)
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
{{trans|MATLAB}}
<langsyntaxhighlight lang="julia">
# String assignment. Creation and garbage collection are automatic.
a = "123\x00 abc " # strings can contain bytes that are not printable in the local font
Line 2,307 ⟶ 2,564:
d = a * b * c
println(d)
</syntaxhighlight>
</lang>
{{output}}<pre>
123 abc
Line 2,323 ⟶ 2,580:
123 abc d456 789
</pre>
 
=={{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.
Line 2,330 ⟶ 2,586:
 
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.
<langsyntaxhighlight lang="scala">class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
val length get() = bytes.size
 
Line 2,419 ⟶ 2,675:
println("ABCDEF with CD replaced by GH is ${bs3.replace("CD".bs, "GH".bs)}")
println("GHI£€ as a ByteString is $bs4")
}</langsyntaxhighlight>
 
{{out}}
Line 2,439 ⟶ 2,695:
GHI£€ as a ByteString is GHI£?
</pre>
 
=={{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.
<syntaxhighlight lang="lb">
<lang lb>
'string creation
s$ = "Hello, world!"
Line 2,476 ⟶ 2,731:
'join strings
s$ = "Good" + "bye" + " for now."
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight Lingolang="lingo">-- String creation and destruction
foo = "Hello world!" -- created by assignment; destruction via garbage collection
 
Line 2,538 ⟶ 2,792:
foo = "Hello" & numtochar(32) & "world!"
foo = "Hello" & SPACE & "world!"
foo = "Hello" && "world!"</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">foo = 'foo' -- Ducktyping foo to be string 'foo'
bar = 'bar'
assert (foo == "foo") -- Comparing string var to string literal
Line 2,571 ⟶ 2,824:
print (str)
 
str = foo .. bar -- Strings concatenate with .. operator</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">(* String creation and destruction *) BinaryString = {}; BinaryString = . ;
(* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65}
-> {12,56,82,65}
Line 2,592 ⟶ 2,844:
-> {12,56,82,65,33,44}
(* Join strings *) BinaryString4 = Join[BinaryString1 , BinaryString2]
-> {12,56,82,65,83,12,56,65}</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
a=['123',0,' abc '];
b=['456',9];
Line 2,632 ⟶ 2,883:
d=[a,b,c];
disp(d);
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,648 ⟶ 2,899:
123 abc @456 789
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var # creation
x = "this is a string"
y = "this is another string"
Line 2,672 ⟶ 2,922:
import strutils
 
echo z.replace('t', 'T') # replace occurences of t with T</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
Line 2,679 ⟶ 2,928:
 
<code>String.create n</code> returns a fresh string of length n, which initially contains arbitrary characters:
<langsyntaxhighlight lang="ocaml"># String.create 10 ;;
- : string = "\000\023\000\000\001\000\000\000\000\000"</langsyntaxhighlight>
 
No destruction, OCaml features a garbage collector.
Line 2,687 ⟶ 2,936:
 
* String assignment
<langsyntaxhighlight lang="ocaml"># let str = "some text" ;;
val str : string = "some text"
 
(* modifying a character, OCaml strings are mutable *)
# str.[0] <- 'S' ;;
- : unit = ()</langsyntaxhighlight>
 
* String comparison
<langsyntaxhighlight lang="ocaml"># str = "Some text" ;;
- : bool = true
 
# "Hello" > "Ciao" ;;
- : bool = true</langsyntaxhighlight>
 
* String cloning and copying
<langsyntaxhighlight lang="ocaml"># String.copy str ;;
- : string = "Some text"</langsyntaxhighlight>
 
* Check if a string is empty
<langsyntaxhighlight lang="ocaml"># let string_is_empty s = (s = "") ;;
val string_is_empty : string -> bool = <fun>
 
Line 2,713 ⟶ 2,962:
 
# string_is_empty "" ;;
- : bool = true</langsyntaxhighlight>
 
* Append a byte to a string
Line 2,722 ⟶ 2,971:
a byte and return the result as a new string
 
<langsyntaxhighlight lang="ocaml"># str ^ "!" ;;
- : string = "Some text!"</langsyntaxhighlight>
 
But OCaml has a module named Buffer for string buffers.
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</langsyntaxhighlight>
 
* Extract a substring from a string
<langsyntaxhighlight lang="ocaml"># String.sub str 5 4 ;;
- : string = "text"</langsyntaxhighlight>
 
* Replace every occurrence of a byte (or a string) in a string with another string
using the '''Str''' module
<langsyntaxhighlight lang="ocaml"># #load "str.cma";;
# let replace str occ by =
Str.global_replace (Str.regexp_string occ) by str
Line 2,742 ⟶ 2,991:
val replace : string -> string -> string -> string = <fun>
# replace "The white dog let out a single, loud bark." "white" "black" ;;
- : string = "The black dog let out a single, loud bark."</langsyntaxhighlight>
 
* Join strings
<langsyntaxhighlight lang="ocaml"># "Now just remind me" ^ " how the horse moves again?" ;;
- : string = "Now just remind me how the horse moves again?"</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
This code accepts arbitrary characters, but you can use <code>Strchr</code> to display ASCII strings.
<langsyntaxhighlight lang="parigp">cmp_str(u,v)=u==v
copy_str(v)=v \\ Creates a copy, not a pointer
append_str(v,n)=concat(v,n)
Line 2,763 ⟶ 3,011:
u[8..12]
replace_str(u,108,[121])
concat(v,w)</langsyntaxhighlight>
{{out}}
<pre>%1 = 0
Line 2,772 ⟶ 3,020:
%6 = [72, 101, 121, 121, 111, 44, 32, 119, 111, 114, 121, 100]
%7 = []</pre>
 
=={{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
<langsyntaxhighlight lang="pascal">const
greeting = 'Hello';
var
Line 2,800 ⟶ 3,047:
{ Join strings}
s3 := greeting + ' and how are you, ' + s1 + '?';
end.</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="perl">$s = undef;
say 'Nothing to see here' if ! defined $s; # 'Nothing to see here'
say $s = ''; # ''
Line 2,815 ⟶ 3,061:
$t =~ s/ee/ook/; say $t; # 'bookkeeper'
say $u = substr $t, 2, 2; # 'ok'
say 'Oklahoma' . ' is ' . uc $u; # 'Oklahoma is OK'</langsyntaxhighlight>
 
=={{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.
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.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>string s = "abc"
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
s = x"ef bb bf" -- explicit binary string (the utf8 BOM)
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"abc"</span>
s[2] = 0
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">x"ef bb bf"</span> <span style="color: #000080;font-style:italic;">-- explicit binary string (the utf8 BOM)</span>
s[3] = 'z'
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if s="\#EF\0z" then puts(1,"ok\n") end if
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'z'</span>
string t = s
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"\#EF\0z"</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ok\n"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
t[1..2] = "xy" -- s remains unaltered
<span style="color: #004080;">string</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
?t -- "xyz"
<span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"xy"</span> <span style="color: #000080;font-style:italic;">-- s remains unaltered</span>
t = "food" ?t
<span style="color: #0000FF;">?</span><span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- "xyz"</span>
t[2..3] = 'e' ?t -- "feed"
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"food"</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">t</span>
t[3..2] = "ast" ?t -- "feasted"
<span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'e'</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- "feed"</span>
t[3..-2] = "" ?t -- "fed"
<span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"ast"</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- "feasted"</span>
if length(t)=0 then puts(1,"t is empty\n") end if
<span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- "fed"</span>
if t!="" then puts(1,"t is not empty\n") end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"t is empty\n"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
t = "be"
<span style="color: #008080;">if</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"t is not empty\n"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
t &= 't' ?t -- bet
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"be"</span>
t = 'a'&t ?t -- abet
<span style="color: #000000;">t</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'t'</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- bet</span>
?t[2..3] -- be
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'a'</span><span style="color: #0000FF;">&</span><span style="color: #000000;">t</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">t</span> <span style="color: #000080;font-style:italic;">-- abet</span>
?substitute(t,"be","bbo") -- abbot
<span style="color: #0000FF;">?</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- be</span>
?substitute(t,"be","dep") -- adept
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"be"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bbo"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- abbot</span>
t = substitute(t,"be","dep") -- to actually modify t
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"be"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"dep"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- adept</span>
?join({"abc","def","ghi"}) -- "abc def ghi"
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"be"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"dep"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- to actually modify t</span>
?join({"abc","def","ghi"},"") -- "abcdefghi"
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"def"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ghi"</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- "abc def ghi"</span>
?join({"abc","def","ghi"},"\n") -- "abc\ndef\nghi"</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"def"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ghi"</span><span style="color: #0000FF;">},</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "abcdefghi"</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"def"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ghi"</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "abc\ndef\nghi"</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,863 ⟶ 3,111:
"abc\ndef\nghi"
</pre>
=={{header|Picat}}==
Strings in Picat are lists of characters.
<syntaxhighlight lang="picat">main => % - String assignment
S1 = "binary_string",
println(s1=S1),
 
% Picat has re-assignments (:=/2) as well,
S1 := "another string",
println(s1=S1),
 
% - String comparison
if S1 == "another string" then
println(same)
else
println(not_same)
end,
% - String cloning and copying
S2 = S1,
println(s2=S2),
S3 = copy_term(S1), % for strings it's the same as =/2
println(s3=S3),
% - Check if a string is empty
if S3 == "" then
println(is_empty)
else
println(not_empty)
end,
 
% - Append a byte to a string
S3 := S3 ++ "s",
println(s3=S3),
% - Extract a substring from a string
println(substring=S3[5..7]),
println(slice=slice(S1,5,7)),
println(slice=slice(S1,5)),
 
% - Replace every occurrence of a byte (or a string) in a string with another string
S4 = replace(S3,'s','x'),
println(s4=S4),
 
% - Join strings
S5 = S1 ++ " " ++ S2,
println(s5=S5),
 
% using append/4
append(S1," ", S2,S6),
println(s6=S6),
 
% find positions of substrings
println(find=findall([From,To],find(S5,"str",From,To))),
 
% split a string
println(split=split(S1," st"))</syntaxhighlight>
 
{{out}}
<pre>s1 = binary_string
s1 = another string
same
s2 = another string
s3 = another string
not_empty
s3 = another strings
substring = her
slice = her
slice = her string
s4 = another xtringx
s5 = another string another string
s6 = another string another string
find = [[9,11],[24,26]]
split = [ano,her,ring]</pre>
 
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 =>
println(member=findall(C,(member(C,S1), C @< 'l') )),
 
% find substrings using append/3
S = "string",
println(append=findall([A,B],append(A,B,S))),
% split around "r"
println(append=findall([A,B],append(A,"r",B,S))),
 
% select a character and returns the list without that character
println(select=findall([C,NewS],select(C,S,NewS))),
 
% list comprehension
println(list_comprehension=[ C : C in S5, membchk(C,"aeiou")]),
% sort and remove duplicates
println(sort_remove_dups=sort_remove_dups(S5)).</syntaxhighlight>
 
{{out}}
<pre>member = ahe ig
append = [[[],string],[s,tring],[st,ring],[str,ing],[stri,ng],[strin,g],[string,[]]]
append = [[st,ing]]
select = [[s,tring],[t,sring],[r,sting],[i,strng],[n,strig],[g,strin]]
list_comprehension = aoeiaoei
sort_remove_dups = aeghinorst</pre>
=={{header|PicoLisp}}==
Byte strings are represented in PicoLisp as lists of numbers. They can be
Line 2,870 ⟶ 3,217:
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:
<langsyntaxhighlight PicoLisplang="picolisp">: (out "rawfile"
(mapc wr (range 0 255)) )</langsyntaxhighlight>
Looking at a hex dump of that file:
<langsyntaxhighlight PicoLisplang="picolisp">: (hd "rawfile")
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 ................
00000020 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F !"#$%&'()*+,-./
00000030 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 0123456789:;<=>?
...</langsyntaxhighlight>
To read part of that file, an external tool like 'dd' might be used:
<langsyntaxhighlight PicoLisplang="picolisp">: (in '(dd "skip=32" "bs=1" "count=16" "if=rawfile")
(make
(while (rd 1)
(link @) ) ) )
-> (32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47)</langsyntaxhighlight>
Now such byte lists can be assigned the normal way ('let', 'setq' etc.), they
can be compared with '=', '>', '>=' etc, and manipulated with all internal map-,
Line 2,891 ⟶ 3,238:
If desired, a string containing meaningful values can also be converted to
a transient symbol, e.g. the example above
<langsyntaxhighlight PicoLisplang="picolisp">: (pack (mapcar char (32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47)))
-> " !\"#$%&'()*+,-./"</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* PL/I has immediate facilities for all those operations except for */
/* replace. */
Line 2,918 ⟶ 3,264:
end;
end replace;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
Clear-Host
 
Line 2,989 ⟶ 3,334:
Write-Host '1..12 | Format-Wide {$_.ToString().PadLeft(2)}-Column 3 -Force' -NoNewline -ForegroundColor Yellow
1..12 | Format-Wide {$_.ToString().PadLeft(2)} -Column 3 -Force
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,050 ⟶ 3,395:
10 11 12
</pre>
 
=={{header|Prolog}}==
 
<langsyntaxhighlight lang="prolog">% Create a string (no destruction necessary)
?- X = "a test string".
X = "a test string".
Line 3,102 ⟶ 3,446:
Y = " with extra!",
Z = "a test string with extra!".
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
;string creation
x$ = "hello world"
Line 3,132 ⟶ 3,475:
; join strings
x$ = "hel" + "lo w" + "orld"
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
===2.x===
Line 3,140 ⟶ 3,482:
* String creation
 
<langsyntaxhighlight lang="python">s1 = "A 'string' literal \n"
s2 = 'You may use any of \' or " as delimiter'
s3 = """This text
goes over several lines
up to the closing triple quote"""</langsyntaxhighlight>
 
* String assignment
Line 3,150 ⟶ 3,492:
There is nothing special about assignments:
 
<langsyntaxhighlight lang="python">s = "Hello "
t = "world!"
u = s + t # + concatenates</langsyntaxhighlight>
 
* String comparison
Line 3,158 ⟶ 3,500:
They're compared byte by byte, lexicographically:
 
<langsyntaxhighlight lang="python">assert "Hello" == 'Hello'
assert '\t' == '\x09'
assert "one" < "two"
assert "two" >= "three"</langsyntaxhighlight>
 
* String cloning and copying
Line 3,169 ⟶ 3,511:
* Check if a string is empty
 
<langsyntaxhighlight lang="python">if x=='': print "Empty string"
if not x: print "Empty string, provided you know x is a string"</langsyntaxhighlight>
 
* Append a byte to a string
 
<langsyntaxhighlight lang="python">txt = "Some text"
txt += '\x07'
# txt refers now to a new string having "Some text\x07"</langsyntaxhighlight>
 
* Extract a substring from a string
Line 3,182 ⟶ 3,524:
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])
 
<langsyntaxhighlight lang="python">txt = "Some more text"
assert txt[4] == " "
assert txt[0:4] == "Some"
assert txt[:4] == "Some" # you can omit the starting index if 0
assert txt[5:9] == "more"
assert txt[5:] == "more text" # omitting the second index means "to the end"</langsyntaxhighlight>
 
Negative indexes count from the end: -1 is the last byte, and so on:
 
<langsyntaxhighlight lang="python">txt = "Some more text"
assert txt[-1] == "t"
assert txt[-4:] == "text"</langsyntaxhighlight>
 
* Replace every occurrence of a byte (or a string) in a string with another string
Line 3,199 ⟶ 3,541:
Strings are objects and have methods, like replace:
 
<langsyntaxhighlight lang="python">v1 = "hello world"
v2 = v1.replace("l", "L")
print v2 # prints heLLo worLd</langsyntaxhighlight>
 
* Join strings
Line 3,207 ⟶ 3,549:
If they're separate variables, use the + operator:
 
<langsyntaxhighlight lang="python">v1 = "hello"
v2 = "world"
msg = v1 + " " + v2</langsyntaxhighlight>
 
If the elements to join are contained inside any iterable container (e.g. a list)
 
<langsyntaxhighlight lang="python">items = ["Smith", "John", "417 Evergreen Av", "Chimichurri", "481-3172"]
joined = ",".join(items)
print joined
# output:
# Smith,John,417 Evergreen Av,Chimichurri,481-3172</langsyntaxhighlight>
 
The reverse operation (split) is also possible:
 
<langsyntaxhighlight lang="python">line = "Smith,John,417 Evergreen Av,Chimichurri,481-3172"
fields = line.split(',')
print fields
# output:
# ['Smith', 'John', '417 Evergreen Av', 'Chimichurri', '481-3172']</langsyntaxhighlight>
 
===3.x===
Line 3,231 ⟶ 3,573:
 
To specify a literal immutable byte string (<code>bytes</code>), prefix a string literal with "b":
<langsyntaxhighlight lang="python">s1 = b"A 'byte string' literal \n"
s2 = b'You may use any of \' or " as delimiter'
s3 = b"""This text
goes over several lines
up to the closing triple quote"""</langsyntaxhighlight>
 
You can use the normal string escape sequences to encode special bytes.
 
Indexing a byte string results in an integer (the byte value at that byte):
<langsyntaxhighlight lang="python">x = b'abc'
x[0] # evaluates to 97</langsyntaxhighlight>
 
Similarly, a byte string can be converted to and from a list of integers:
 
<langsyntaxhighlight lang="python">x = b'abc'
list(x) # evaluates to [97, 98, 99]
bytes([97, 98, 99]) # evaluates to b'abc'</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,299 ⟶ 3,640:
 
(bytes-join (list b2 b3) #" ") ; -> #"BBBBB BAAAA"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line># Raku is perfectly fine with NUL *characters* in strings:
my Str $s = 'nema' ~ 0.chr ~ 'problema!';
say $s;
Line 3,386 ⟶ 3,726:
# joining:
my ByteStr $b3 = $b1 ~ $sub;
say 'joined = ', $b3;</langsyntaxhighlight>
 
{{out}}
Line 3,404 ⟶ 3,744:
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>
 
=={{header|Red}}==
<langsyntaxhighlight Rebollang="rebol">Red []
s: copy "abc" ;; string creation
 
Line 3,424 ⟶ 3,763:
s: rejoin ["hello " "world" " !"] ;; join multiple strings
?? s
</syntaxhighlight>
</lang>
{{out}}
<pre>equal (case insensitive)
Line 3,434 ⟶ 3,773:
>>
</pre>
 
=={{header|REXX}}==
Programming note: &nbsp; this REXX example demonstrates two types of &nbsp; ''quoting''.
<langsyntaxhighlight REXXlang="rexx">/*REXX program demonstrates methods (code examples) to use and express binary strings.*/
dingsta= '11110101'b /*four versions, bit string assignment.*/
dingsta= "11110101"b /*this is the same assignment as above.*/
Line 3,453 ⟶ 3,791:
tt= changeStr('~~', other, ";") /*change two tildes ──► one semicolon.*/
joined= dingsta || dingsta2 /*join two strings together (concat). */
say joined c2b(joined)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
c2b: returnReturn x2b( c2x( arg(1) )) ) /*return the string as a binary string.*/</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
{{out}}
<pre>§§ 1111010111110101</pre>
 
=={{header|Ring}}==
The String in the Ring programming language holds and manipulates an arbitrary sequence of bytes.
 
<langsyntaxhighlight lang="ring"># string creation
x = "hello world"
Line 3,505 ⟶ 3,846:
c = "orld"
See a + b + c
</syntaxhighlight>
</lang>
=={{header|RPL}}==
Strings are a sequence of bytes.
 
String creation:
"This is a new string" <span style="color:grey">@ String is put at stack level 1</span>
No need for destruction as there is a garbage collection mechanism.
 
String assignment:
"This is a string" '<span style="color:green">MYTEXT</span>' STO <span style="color:grey">@ String is transferred from stack level 1 to MYTEXT variable</span>
String comparison: numeric operators can be used for equality or lexicographic order
"This" "That" == <span style="color:grey">@ test equality - returns 0 here</span>
"This" "That" > <span style="color:grey">@ test order - returns 1 here</span>
Inclusion can also be tested:
"This" "is" POS <span style="color:grey">@ returns position of substring - 3 here</span>
String cloning and copying: any object, including strings, can be duplicated in the stack:
"This" DUP <span style="color:grey">@ Put a copy of "This" at stack level #2</span>
Check if a string is empty:
<span style="color:green">MYTEXT</span> "" == <span style="color:grey">@ returns 1 if MYTEXT contains an empty string</span>
or
<span style="color:green">MYTEXT</span> SIZE NOT <span style="color:grey">@ returns 1 if MYTEXT contains an empty string</span>
Append a byte to a string:
"Thi" "s" +
Extract a substring from a string:
"This is a string" 2 4 SUB <span style="color:grey">@ returns substring from 2nd to 4th character</span>
Replace every occurrence of a byte (or a string) in a string with another string: we need a small program here, since the REPL function replaces only the first occurence of the searched substring
≪ → string old new <span style="color:grey">@ store arguments</span>
≪ string <span style="color:grey">@ put string to be replaced in stack</span>
'''WHILE''' DUP old POS '''REPEAT''' <span style="color:grey">@ while old is present in string</span>
LAST SWAP new REPL <span style="color:grey">@ replace old by new</span>
'''END'''
≫ ≫ '<span style="color:blue">REPLALL</span>' STO
Join strings:
"This is" " a string" +
 
=={{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.
<langsyntaxhighlight lang="ruby"># string creation
x = "hello world"
Line 3,555 ⟶ 3,929:
b = "lo w"
c = "orld"
p d = a + b + c</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">' Create string
s$ = "Hello, world"
Line 3,590 ⟶ 3,964:
'join strings
s$ = "See " + "you " + "later."
print s$</langsyntaxhighlight>
 
=={{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].
<langsyntaxhighlight lang="rust">use std::str;
 
fn main() {
Line 3,664 ⟶ 4,037:
let split_str: Vec<_> = f_str.split(' ').collect();
assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split");
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Seed7 strings are capable to hold binary data.
Line 3,727 ⟶ 4,099:
The [http://seed7.sourceforge.net/libraries/string.htm string.s7i] library contains
more string functions.
 
=={{header|Smalltalk}}==
Smalltalk strings are variable length and unrestricted. They are builtin and no additional library is req'd.
 
<langsyntaxhighlight Smalltalklang="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 := String new:3. # a mutable string
Line 3,751 ⟶ 4,122:
s2 := s1 , $x # append a character
s2 := s1 , 123 asCharacter # append an arbitrary byte
s := 'Hello / 今日は' # they support unicode (at least up to 16rFFFF, some more)</langsyntaxhighlight>
 
In addition (because they inherit from collection), a lot more is inherited (map, fold, enumeration, finding substrings, etc.)
 
=={{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>.
<langsyntaxhighlight lang="tcl"># string creation
set x "hello world"
 
Line 3,792 ⟶ 4,162:
set b "lo w"
set c "orld"
set d $a$b$c</langsyntaxhighlight>
 
=={{header|VBA}}==
Before start, see this link :
Line 3,800 ⟶ 4,169:
The default text comparison method is Binary.
</pre>
<syntaxhighlight lang="vb">
<lang vb>
'Set the string comparison method to Binary.
Option Compare Binary ' That is, "AAA" is less than "aaa".
' Set the string comparison method to Text.
Option Compare Text ' That is, "AAA" is equal to "aaa".</langsyntaxhighlight>
String creation and destruction :
<syntaxhighlight lang="vb">
<lang vb>
Sub Creation_String_FirstWay()
Dim myString As String
'Here, myString is created and equal ""
End Sub '==> Here the string is destructed !</langsyntaxhighlight>
String assignment :
<langsyntaxhighlight lang="vb">Sub String_Assignment()
Dim myString$
'Here, myString is created and equal ""
Line 3,821 ⟶ 4,190:
myString = "Hello World" 'return : "Hello World"
myString = String(12, "A") 'return : "AAAAAAAAAAAA"
End Sub</langsyntaxhighlight>
String comparison :
<langsyntaxhighlight lang="vb">Sub String_Comparison_FirstWay()
Dim A$, B$, C$
 
Line 3,850 ⟶ 4,219:
'See Also :
'https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/like-operator
End Sub</langsyntaxhighlight>
String cloning and copying :
<langsyntaxhighlight lang="vb">Sub String_Clone_Copy()
Dim A As String, B$
A = "Hello world!"
'cloning :
B = A
End Sub</langsyntaxhighlight>
Check if a string is empty :
<langsyntaxhighlight lang="vb">Sub Check_Is_Empty()
Dim A As String, B As Variant
 
Line 3,881 ⟶ 4,250:
Debug.Print A = "" 'return True
'Note : StrPtr is the only way to know if you cancel the inputbox
End Sub</langsyntaxhighlight>
Append a byte to a string :
<langsyntaxhighlight lang="vb">Sub Append_to_string()
Dim A As String
A = "Hello worl"
Debug.Print A & Chr(100) 'return : Hello world
End Sub</langsyntaxhighlight>
Extract a substring from a string :
<langsyntaxhighlight lang="vb">Sub ExtractFromString()
Dim A$, B As String
A = "Hello world"
B = Mid(A, 3, 8)
Debug.Print B 'return : llo worl
End Sub</langsyntaxhighlight>
Replace every occurrence of a byte (or a string) in a string with another string :
<langsyntaxhighlight lang="vb">Sub ReplaceInString()
Dim A$, B As String, C$
A = "Hello world"
Line 3,902 ⟶ 4,271:
C = " "
Debug.Print Replace(A, B, C) 'return : He o wor d
End Sub</langsyntaxhighlight>
Join Strings :
<langsyntaxhighlight lang="vb">Sub Join_Strings()
Dim A$, B As String
 
Line 3,913 ⟶ 4,282:
Debug.Print A + " " + B 'return : Hello world
End Sub
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 3,982 ⟶ 4,350:
End Sub
 
End Module</langsyntaxhighlight>
 
=={{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.
Line 3,996 ⟶ 4,363:
 
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.
<langsyntaxhighlight ecmascriptlang="wren">// create string
var s = "abc"
 
Line 4,030 ⟶ 4,397:
s = "abc"
t = "def"
var u = s + t // "abcdef"</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Binary_strings
// by Galileo, 07/2022
 
// Create string
s$ = "Hello, world"
// String destruction
s$ = ""
// String comparison
If s$ = "Hello, world" print "Equal String"
// Copying string
a$ = s$
// Check If empty
If s$ = "" print "String is MT"
// Append a byte
s$ = s$ + Chr$(65)
// Extract a substring
a$ = Mid$(s$, 1, 5) // bytes 1 -> 5
//substitute string "world" with "universe"
a$ = "Hello, world"
for i = 1 to len(a$)
if mid$(a$,i,5)="world" then
a$=left$(a$,i-1)+"universe"+mid$(a$,i+5)
end if
next
print a$
//join strings
s$ = "See " + "you " + "later."
print s$</syntaxhighlight>
{{out}}
<pre>String is MT
Hello, universe
See you later.
---Program done, press RETURN---</pre>
=={{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.
<langsyntaxhighlight lang="zkl">Data(0,.Int,1,2,3) // bytes
Data(0,String,1,2,3) // same
Data(0,Int,"foo","bar") //-->foobar\0
Line 4,054 ⟶ 4,463:
 
d2:=Data(0,Int,"sam");
d.append(d2).text // or d+d2</langsyntaxhighlight>
 
{{omit from|GUISS}}
{{omit from|Lotus 123 Macro Scripting}}
9,476

edits