Binary strings: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 21:
Possible contexts of use: compression algorithms (like [[LZW compression]]), L-systems (manipulation of symbols), many more.
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">V x = Bytes(‘abc’)
print(x[0])</syntaxhighlight>
 
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.)
Line 36 ⟶ 34:
===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.
<syntaxhighlight lang="asm">;this code assumes that both DS and ES point to the correct segments.
cld
mov si,offset TestMessage
Line 50 ⟶ 48:
 
===Checking if a particular byte exists===
<syntaxhighlight lang="asm">;this code assumes that ES points to the correct segment.
cld
mov di,offset TestMessage
Line 63 ⟶ 61:
 
===Compare two strings===
<syntaxhighlight lang="asm">;this code assumes that both DS and ES point to the correct segments.
cld
mov si,offset foo
Line 77 ⟶ 75:
foo byte "test"
bar byte "test"</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang=Ada"ada">declare
Data : Storage_Array (1..20); -- Data created
begin
Line 99 ⟶ 96:
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:
<syntaxhighlight lang=Ada"ada">type Octet is mod 2**8;
for Octet'Size use 8;
type Octet_String is array (Positive range <>) of Octet;</syntaxhighlight>
Alternatively:
<syntaxhighlight lang=Ada"ada">with Interfaces; use Interfaces;
...
type Octet is new Interfaces.Unsigned_8;
type Octet_String is array (Positive range <>) of Octet;</syntaxhighlight>
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}} -->
<syntaxhighlight lang="algol68"># String creation #
STRING a,b,c,d,e,f,g,h,i,j,l,r;
a := "hello world";
Line 229 ⟶ 225:
7th byte in CPU word is: w
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; creation
x: "this is a string"
y: "this is another string"
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}}==
<syntaxhighlight lang=AWK"awk">#!/usr/bin/awk -f
 
BEGIN {
Line 325 ⟶ 319:
d=<123 abc @456 789>
</pre>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang=ApplesoftBasic"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 360 ⟶ 353:
==={{header|GW-BASIC}}===
Also works in QBASIC, QuickBASIC, VB-DOS and PDS 7.1
<syntaxhighlight lang=QBASIC"qbasic">
10 ' SAVE"BINSTR", A
20 ' This program does string manipulation
Line 377 ⟶ 370:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS"is-BASICbasic">100 RANDOMIZE
110 REM create two strings
120 LET S$="Hello":LET T$="Bob"
Line 392 ⟶ 385:
 
==={{header|OxygenBasic}}===
<syntaxhighlight lang="text">
'STRING CREATION AND DESTRUCTION
string A
Line 437 ⟶ 430:
 
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="basic">10 REM create two strings
20 LET s$ = "Hello"
30 LET t$ = "Bob"
Line 450 ⟶ 443:
120 REM print characters 2 to 4 of a string (a substring)
130 PRINT s$(2 TO 4)</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<syntaxhighlight 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 468 ⟶ 460:
UNTIL I% = 0
</syntaxhighlight>
 
 
=={{header|BQN}}==
 
Line 477 ⟶ 467:
 
* Example binary string creation
<syntaxhighlight lang="bqn"> name ← ""</syntaxhighlight>
 
* Example binary string deletion: effectively replaces the data with an integer, removing it from an accessible name.
<syntaxhighlight lang="bqn"> name ↩ 0</syntaxhighlight>
 
* Example binary string assignment
<syntaxhighlight lang="bqn"> name ← "value"</syntaxhighlight>
 
* Example binary string comparison
<syntaxhighlight lang="bqn"> name1 ≡ name2</syntaxhighlight>
 
* Example binary string cloning and copying
<syntaxhighlight lang="bqn"> name1 ← "example"
name2 ← name1</syntaxhighlight>
 
* Example check if a binary string is empty
<syntaxhighlight lang="bqn"> 0=≠string</syntaxhighlight>
 
* Example apppend a byte to a binary string
<syntaxhighlight lang="bqn"> string ← "example"
byte ← @
string ∾↩ byte</syntaxhighlight>
 
* Extract a substring from a binary string
<syntaxhighlight lang="bqn"> 3↓¯5↓"The quick brown fox runs..."</syntaxhighlight>
 
* Join strings
<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.
<syntaxhighlight lang="bqn"> n + @</syntaxhighlight>
 
Thus, the binary string containing bytes with numeric values 1 0 255 can be obtained this way:
<syntaxhighlight lang="bqn">1‿0‿255 + @</syntaxhighlight>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 651 ⟶ 640:
return 0;
}</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++}}==
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 729 ⟶ 785:
hello
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}}==
String creation (garbage collection will handle its destruction)
using the string as an atom and casting a character list to a string
<syntaxhighlight lang="lisp">
"string"
(coerce '(#\s #\t #\r #\i #\n #\g) 'string)
Line 808 ⟶ 794:
 
String assignment
<syntaxhighlight lang="lisp">
(defvar *string* "string")
</syntaxhighlight>
 
comparing two string
<syntaxhighlight lang="lisp">
(equal "string" "string")
</syntaxhighlight>
 
copy a string
<syntaxhighlight lang="lisp">
(copy-seq "string")
</syntaxhighlight>
 
<syntaxhighlight lang="lisp">
(defun string-empty-p (string)
(zerop (length string)))</syntaxhighlight>
 
<syntaxhighlight lang="lisp">
(concatenate 'string "string" "b")
</syntaxhighlight>
 
<syntaxhighlight lang="lisp">
(subseq "string" 2 6)
"ring"
Line 839 ⟶ 825:
 
joining strings works in the same way as appending bytes
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE NpctBinaryString;
IMPORT StdLog,Strings;
Line 922 ⟶ 907:
pStr + '.' + pAux:>First string.Second String
</pre>
 
=={{header|D}}==
<syntaxhighlight lang="d">void main() /*@safe*/ {
import std.array: empty, replace;
import std.string: representation, assumeUTF;
Line 969 ⟶ 953:
ubyte[] str3 = str1 ~ str2;
}</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}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi"delphi">
program Binary_strings;
 
Line 1,076 ⟶ 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,085 ⟶ 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).
 
<syntaxhighlight lang="e">? def int8 := <type:java.lang.Byte>
# value: int8</syntaxhighlight>
 
<ol>
<li>There are several ways to create a FlexList; perhaps the simplest is:
<syntaxhighlight lang="e">? def bstr := [].diverge(int8)
# value: [].diverge()
 
Line 1,101 ⟶ 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 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()
# value: false</syntaxhighlight>
</li><li>To make an independent copy of a FlexList, simply <code>.diverge()</code> it again.
</li><li><syntaxhighlight lang="e">? bstr1.size().isZero()
# value: false
 
Line 1,110 ⟶ 1,092:
# value: true</syntaxhighlight>
</li><li>Appending a single element to a FlexList is done by <code>.push(<var>x</var>)</code>:
<syntaxhighlight lang="e">? bstr.push(0)
? bstr
# 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>.
<syntaxhighlight lang="e">? bstr1(1, 2)
# value: [2]
 
Line 1,121 ⟶ 1,103:
# 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).
<syntaxhighlight lang="e">? for i => byte ? (byte == 2) in bstr2 { bstr2[i] := -1 }
? bstr2
# 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.
<syntaxhighlight lang="e">? bstr1.append(bstr2)
? bstr1
# value: [1, 2, 3, -127, 2, 3].diverge()</syntaxhighlight>
</li></ol>
 
=={{header|Elixir}}==
Note: Elixir data types are immutable.
<syntaxhighlight lang="elixir"># String creation
x = "hello world"
 
Line 1,187 ⟶ 1,168:
c = "orld"
IO.puts a <> b <> c #=> hello world</syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">-module(binary_string).
-compile([export_all]).
 
Line 1,239 ⟶ 1,219:
replace(Rest,Value,Replacement,<< Acc/binary, Keep >>).</syntaxhighlight>
{{out}}
<syntaxhighlight 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,249 ⟶ 1,229:
Append: <<0,1,1,2,3,5,8,13,21>>
Join: <<0,1,1,2,3,5,8,13,21,34,55>></syntaxhighlight>
 
=={{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:
<syntaxhighlight lang="factor">"Hello, byte-array!" utf8 encode .</syntaxhighlight>
<pre>
B{
Line 1,261 ⟶ 1,240:
</pre>
Reverse:
<syntaxhighlight lang="factor">B{ 147 250 150 123 } shift-jis decode .</syntaxhighlight>
<pre>"日本"</pre>
 
=={{header|Forth}}==
In Forth, as in Assembler, all strings are binary ie: they are simply bytes in memory. <br>
Line 1,273 ⟶ 1,251:
 
<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
 
Line 1,375 ⟶ 1,353:
at the Forth console to see if we have satisfied the Rosetta code requirements
 
<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)
Line 1,502 ⟶ 1,480:
 
</syntaxhighlight>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Dim As String cad, cad2
'creación de cadenas
Line 1,546 ⟶ 1,522:
Sleep
</syntaxhighlight>
 
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 1,647 ⟶ 1,621:
bary
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">import java.nio.charset.StandardCharsets
 
class MutableByteString {
Line 1,771 ⟶ 1,744:
 
Test Code
<syntaxhighlight lang="groovy">import org.testng.Assert
import org.testng.annotations.Test
 
Line 1,830 ⟶ 1,803:
}
}</syntaxhighlight>
 
=={{header|Haskell}}==
Note that any of the following functions can be assigned
Line 1,842 ⟶ 1,814:
as Haskell can be somewhat intimidating to the (currently) non-
functional programmer.
<syntaxhighlight 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,852 ⟶ 1,824:
string = "world" :: String</syntaxhighlight>
 
<syntaxhighlight lang="haskell">{- Comparing two given strings and
returning a boolean result using a
simple conditional -}
Line 1,861 ⟶ 1,833:
else False</syntaxhighlight>
 
<syntaxhighlight 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,870 ⟶ 1,842:
else False</syntaxhighlight>
 
<syntaxhighlight lang="haskell">{- This is the most obvious way to
append strings, using the built-in
(++) concatenation operator
Line 1,879 ⟶ 1,851:
strAppend x y = x ++ y</syntaxhighlight>
 
<syntaxhighlight lang="haskell">{- Take the specified number of characters
from the given string -}
strExtract :: Int -> String -> String
strExtract x s = take x s</syntaxhighlight>
 
<syntaxhighlight 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)</syntaxhighlight>
 
<syntaxhighlight 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</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=Icon"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,913 ⟶ 1,884:
 
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"icon">procedure replace(s1, s2, s3) #: string replacement
local result, i
 
Line 1,929 ⟶ 1,900:
 
end</syntaxhighlight>
 
=={{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
<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):
<syntaxhighlight lang="j"> name=: 0</syntaxhighlight>
 
* Example binary string assignment
<syntaxhighlight lang="j"> name=: 'value'</syntaxhighlight>
 
* Example binary string comparison
<syntaxhighlight lang="j"> name1 -: name2</syntaxhighlight>
 
* Example binary string cloning and copying
<syntaxhighlight lang="j"> name1=: 'example'
name2=: name1</syntaxhighlight>
 
Line 1,952 ⟶ 1,922:
 
* Example check if a binary string is empty
<syntaxhighlight lang="j"> 0=#string</syntaxhighlight>
 
* Example apppend a byte to a binary string
<syntaxhighlight lang="j"> string=: 'example'
byte=: DEL
string=: string,byte</syntaxhighlight>
 
* Extract a substring from a binary string
<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
<syntaxhighlight lang="j">require 'strings'
'The quick brown fox runs...' rplc ' ';' !!! '</syntaxhighlight>
 
* Join strings
<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.:
<syntaxhighlight lang="j"> n{a.</syntaxhighlight>
 
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>
 
=={{header|Java}}==
 
<syntaxhighlight lang="java">import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
Line 2,098 ⟶ 2,067:
Test code:
 
<syntaxhighlight lang="java">import static org.hamcrest.CoreMatchers.is;
 
import java.nio.charset.StandardCharsets;
Line 2,158 ⟶ 2,127:
}
}</syntaxhighlight>
 
=={{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
<syntaxhighlight lang=JavaScript"javascript">//String creation
var str='';
//or
Line 2,216 ⟶ 2,184:
str3+str4;
str.concat('\n',str4); //concantenate them</syntaxhighlight>
 
=={{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:<syntaxhighlight lang="jq"># If the input is a valid representation of a binary string
# then pass it along:
def check_binary:
Line 2,232 ⟶ 2,199:
end );</syntaxhighlight>
Examples
<syntaxhighlight lang="jq">## Creation of an entity representing an empty binary string
 
[]
Line 2,303 ⟶ 2,270:
if $byte == x then . + a else . + [$byte] end)
</syntaxhighlight>
 
=={{header|Julia}}==
{{trans|MATLAB}}
<syntaxhighlight 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,368 ⟶ 2,334:
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,375 ⟶ 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.
<syntaxhighlight lang="scala">class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
val length get() = bytes.size
 
Line 2,484 ⟶ 2,449:
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">
'string creation
s$ = "Hello, world!"
Line 2,522 ⟶ 2,486:
s$ = "Good" + "bye" + " for now."
</syntaxhighlight>
 
=={{header|Lingo}}==
<syntaxhighlight lang=Lingo"lingo">-- String creation and destruction
foo = "Hello world!" -- created by assignment; destruction via garbage collection
 
Line 2,584 ⟶ 2,547:
foo = "Hello" & SPACE & "world!"
foo = "Hello" && "world!"</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">foo = 'foo' -- Ducktyping foo to be string 'foo'
bar = 'bar'
assert (foo == "foo") -- Comparing string var to string literal
Line 2,617 ⟶ 2,579:
 
str = foo .. bar -- Strings concatenate with .. operator</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"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,638 ⟶ 2,599:
(* Join strings *) BinaryString4 = Join[BinaryString1 , BinaryString2]
-> {12,56,82,65,83,12,56,65}</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab"matlab">
a=['123',0,' abc '];
b=['456',9];
Line 2,693 ⟶ 2,653:
123 abc @456 789
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">var # creation
x = "this is a string"
y = "this is another string"
Line 2,718 ⟶ 2,677:
 
echo z.replace('t', 'T') # replace occurences of t with T</syntaxhighlight>
 
=={{header|OCaml}}==
 
Line 2,724 ⟶ 2,682:
 
<code>String.create n</code> returns a fresh string of length n, which initially contains arbitrary characters:
<syntaxhighlight lang="ocaml"># String.create 10 ;;
- : string = "\000\023\000\000\001\000\000\000\000\000"</syntaxhighlight>
 
Line 2,732 ⟶ 2,690:
 
* String assignment
<syntaxhighlight lang="ocaml"># let str = "some text" ;;
val str : string = "some text"
 
Line 2,740 ⟶ 2,698:
 
* String comparison
<syntaxhighlight lang="ocaml"># str = "Some text" ;;
- : bool = true
 
Line 2,747 ⟶ 2,705:
 
* String cloning and copying
<syntaxhighlight lang="ocaml"># String.copy str ;;
- : string = "Some text"</syntaxhighlight>
 
* Check if a string is empty
<syntaxhighlight lang="ocaml"># let string_is_empty s = (s = "") ;;
val string_is_empty : string -> bool = <fun>
 
Line 2,767 ⟶ 2,725:
a byte and return the result as a new string
 
<syntaxhighlight lang="ocaml"># str ^ "!" ;;
- : string = "Some text!"</syntaxhighlight>
 
Line 2,773 ⟶ 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).
 
<syntaxhighlight lang="ocaml">Buffer.add_char str c</syntaxhighlight>
 
* Extract a substring from a string
<syntaxhighlight lang="ocaml"># String.sub str 5 4 ;;
- : string = "text"</syntaxhighlight>
 
* Replace every occurrence of a byte (or a string) in a string with another string
using the '''Str''' module
<syntaxhighlight lang="ocaml"># #load "str.cma";;
# let replace str occ by =
Str.global_replace (Str.regexp_string occ) by str
Line 2,790 ⟶ 2,748:
 
* Join strings
<syntaxhighlight lang="ocaml"># "Now just remind me" ^ " how the horse moves again?" ;;
- : string = "Now just remind me how the horse moves again?"</syntaxhighlight>
 
=={{header|PARI/GP}}==
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
copy_str(v)=v \\ Creates a copy, not a pointer
append_str(v,n)=concat(v,n)
Line 2,817 ⟶ 2,774:
%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
<syntaxhighlight lang="pascal">const
greeting = 'Hello';
var
Line 2,846 ⟶ 2,802:
s3 := greeting + ' and how are you, ' + s1 + '?';
end.</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="perl">$s = undef;
say 'Nothing to see here' if ! defined $s; # 'Nothing to see here'
say $s = ''; # ''
Line 2,861 ⟶ 2,816:
say $u = substr $t, 2, 2; # 'ok'
say 'Oklahoma' . ' is ' . uc $u; # 'Oklahoma is OK'</syntaxhighlight>
 
=={{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"phix">(phixonline)-->
<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>
Line 2,911 ⟶ 2,865:
"abc\ndef\nghi"
</pre>
 
=={{header|Picat}}==
Strings in Picat are lists of characters.
<syntaxhighlight lang=Picat"picat">main => % - String assignment
S1 = "binary_string",
println(s1=S1),
Line 2,988 ⟶ 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:
<syntaxhighlight lang=Picat"picat">main =>
println(member=findall(C,(member(C,S1), C @< 'l') )),
 
Line 3,012 ⟶ 2,965:
list_comprehension = aoeiaoei
sort_remove_dups = aeghinorst</pre>
 
 
=={{header|PicoLisp}}==
Byte strings are represented in PicoLisp as lists of numbers. They can be
Line 3,020 ⟶ 2,971:
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:
<syntaxhighlight lang=PicoLisp"picolisp">: (out "rawfile"
(mapc wr (range 0 255)) )</syntaxhighlight>
Looking at a hex dump of that file:
<syntaxhighlight lang=PicoLisp"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 ................
Line 3,030 ⟶ 2,981:
...</syntaxhighlight>
To read part of that file, an external tool like 'dd' might be used:
<syntaxhighlight lang=PicoLisp"picolisp">: (in '(dd "skip=32" "bs=1" "count=16" "if=rawfile")
(make
(while (rd 1)
Line 3,041 ⟶ 2,992:
If desired, a string containing meaningful values can also be converted to
a transient symbol, e.g. the example above
<syntaxhighlight lang=PicoLisp"picolisp">: (pack (mapcar char (32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47)))
-> " !\"#$%&'()*+,-./"</syntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii">
/* PL/I has immediate facilities for all those operations except for */
/* replace. */
Line 3,069 ⟶ 3,019:
end replace;
</syntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">
Clear-Host
 
Line 3,200 ⟶ 3,149:
10 11 12
</pre>
 
=={{header|Prolog}}==
 
<syntaxhighlight lang="prolog">% Create a string (no destruction necessary)
?- X = "a test string".
X = "a test string".
Line 3,253 ⟶ 3,201:
Z = "a test string with extra!".
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">
;string creation
x$ = "hello world"
Line 3,283 ⟶ 3,230:
x$ = "hel" + "lo w" + "orld"
</syntaxhighlight>
 
=={{header|Python}}==
===2.x===
Line 3,290 ⟶ 3,236:
* String creation
 
<syntaxhighlight lang="python">s1 = "A 'string' literal \n"
s2 = 'You may use any of \' or " as delimiter'
s3 = """This text
Line 3,300 ⟶ 3,246:
There is nothing special about assignments:
 
<syntaxhighlight lang="python">s = "Hello "
t = "world!"
u = s + t # + concatenates</syntaxhighlight>
Line 3,308 ⟶ 3,254:
They're compared byte by byte, lexicographically:
 
<syntaxhighlight lang="python">assert "Hello" == 'Hello'
assert '\t' == '\x09'
assert "one" < "two"
Line 3,319 ⟶ 3,265:
* Check if a string is empty
 
<syntaxhighlight lang="python">if x=='': print "Empty string"
if not x: print "Empty string, provided you know x is a string"</syntaxhighlight>
 
* Append a byte to a string
 
<syntaxhighlight lang="python">txt = "Some text"
txt += '\x07'
# txt refers now to a new string having "Some text\x07"</syntaxhighlight>
Line 3,332 ⟶ 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])
 
<syntaxhighlight lang="python">txt = "Some more text"
assert txt[4] == " "
assert txt[0:4] == "Some"
Line 3,341 ⟶ 3,287:
Negative indexes count from the end: -1 is the last byte, and so on:
 
<syntaxhighlight lang="python">txt = "Some more text"
assert txt[-1] == "t"
assert txt[-4:] == "text"</syntaxhighlight>
Line 3,349 ⟶ 3,295:
Strings are objects and have methods, like replace:
 
<syntaxhighlight lang="python">v1 = "hello world"
v2 = v1.replace("l", "L")
print v2 # prints heLLo worLd</syntaxhighlight>
Line 3,357 ⟶ 3,303:
If they're separate variables, use the + operator:
 
<syntaxhighlight lang="python">v1 = "hello"
v2 = "world"
msg = v1 + " " + v2</syntaxhighlight>
Line 3,363 ⟶ 3,309:
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"]
joined = ",".join(items)
print joined
Line 3,371 ⟶ 3,317:
The reverse operation (split) is also possible:
 
<syntaxhighlight lang="python">line = "Smith,John,417 Evergreen Av,Chimichurri,481-3172"
fields = line.split(',')
print fields
Line 3,381 ⟶ 3,327:
 
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"
s2 = b'You may use any of \' or " as delimiter'
s3 = b"""This text
Line 3,390 ⟶ 3,336:
 
Indexing a byte string results in an integer (the byte value at that byte):
<syntaxhighlight lang="python">x = b'abc'
x[0] # evaluates to 97</syntaxhighlight>
 
Similarly, a byte string can be converted to and from a list of integers:
 
<syntaxhighlight lang="python">x = b'abc'
list(x) # evaluates to [97, 98, 99]
bytes([97, 98, 99]) # evaluates to b'abc'</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 3,450 ⟶ 3,395:
(bytes-join (list b2 b3) #" ") ; -> #"BBBBB BAAAA"
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" line># Raku is perfectly fine with NUL *characters* in strings:
my Str $s = 'nema' ~ 0.chr ~ 'problema!';
say $s;
Line 3,554 ⟶ 3,498:
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}}==
<syntaxhighlight lang=Rebol"rebol">Red []
s: copy "abc" ;; string creation
 
Line 3,584 ⟶ 3,527:
>>
</pre>
 
=={{header|REXX}}==
Programming note: &nbsp; this REXX example demonstrates two types of &nbsp; ''quoting''.
<syntaxhighlight lang=REXX"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,608 ⟶ 3,550:
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
 
=={{header|Ring}}==
The String in the Ring programming language holds and manipulates an arbitrary sequence of bytes.
 
<syntaxhighlight lang="ring"># string creation
x = "hello world"
Line 3,656 ⟶ 3,597:
See a + b + c
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="ruby"># string creation
x = "hello world"
Line 3,706 ⟶ 3,646:
c = "orld"
p d = a + b + c</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">' Create string
s$ = "Hello, world"
Line 3,741 ⟶ 3,680:
s$ = "See " + "you " + "later."
print s$</syntaxhighlight>
 
=={{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].
<syntaxhighlight lang="rust">use std::str;
 
fn main() {
Line 3,815 ⟶ 3,753:
assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split");
}</syntaxhighlight>
 
=={{header|Seed7}}==
Seed7 strings are capable to hold binary data.
Line 3,877 ⟶ 3,814:
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.
 
<syntaxhighlight lang=Smalltalk"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,904 ⟶ 3,840:
 
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>.
<syntaxhighlight lang="tcl"># string creation
set x "hello world"
 
Line 3,943 ⟶ 3,878:
set c "orld"
set d $a$b$c</syntaxhighlight>
 
=={{header|VBA}}==
Before start, see this link :
Line 3,950 ⟶ 3,884:
The default text comparison method is Binary.
</pre>
<syntaxhighlight lang="vb">
'Set the string comparison method to Binary.
Option Compare Binary ' That is, "AAA" is less than "aaa".
Line 3,956 ⟶ 3,890:
Option Compare Text ' That is, "AAA" is equal to "aaa".</syntaxhighlight>
String creation and destruction :
<syntaxhighlight lang="vb">
Sub Creation_String_FirstWay()
Dim myString As String
Line 3,963 ⟶ 3,897:
End Sub '==> Here the string is destructed !</syntaxhighlight>
String assignment :
<syntaxhighlight lang="vb">Sub String_Assignment()
Dim myString$
'Here, myString is created and equal ""
Line 3,973 ⟶ 3,907:
End Sub</syntaxhighlight>
String comparison :
<syntaxhighlight lang="vb">Sub String_Comparison_FirstWay()
Dim A$, B$, C$
 
Line 4,002 ⟶ 3,936:
End Sub</syntaxhighlight>
String cloning and copying :
<syntaxhighlight lang="vb">Sub String_Clone_Copy()
Dim A As String, B$
A = "Hello world!"
Line 4,009 ⟶ 3,943:
End Sub</syntaxhighlight>
Check if a string is empty :
<syntaxhighlight lang="vb">Sub Check_Is_Empty()
Dim A As String, B As Variant
 
Line 4,033 ⟶ 3,967:
End Sub</syntaxhighlight>
Append a byte to a string :
<syntaxhighlight lang="vb">Sub Append_to_string()
Dim A As String
A = "Hello worl"
Line 4,039 ⟶ 3,973:
End Sub</syntaxhighlight>
Extract a substring from a string :
<syntaxhighlight lang="vb">Sub ExtractFromString()
Dim A$, B As String
A = "Hello world"
Line 4,046 ⟶ 3,980:
End Sub</syntaxhighlight>
Replace every occurrence of a byte (or a string) in a string with another string :
<syntaxhighlight lang="vb">Sub ReplaceInString()
Dim A$, B As String, C$
A = "Hello world"
Line 4,054 ⟶ 3,988:
End Sub</syntaxhighlight>
Join Strings :
<syntaxhighlight lang="vb">Sub Join_Strings()
Dim A$, B As String
 
Line 4,064 ⟶ 3,998:
End Sub
</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 4,133 ⟶ 4,066:
 
End Module</syntaxhighlight>
 
=={{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 4,146 ⟶ 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.
<syntaxhighlight lang="ecmascript">// create string
var s = "abc"
 
Line 4,181 ⟶ 4,113:
t = "def"
var u = s + t // "abcdef"</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Binary_strings
// by Galileo, 07/2022
 
Line 4,224 ⟶ 4,155:
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.
<syntaxhighlight 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,248 ⟶ 4,178:
d2:=Data(0,Int,"sam");
d.append(d2).text // or d+d2</syntaxhighlight>
 
{{omit from|GUISS}}
{{omit from|Lotus 123 Macro Scripting}}
10,327

edits