Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Binary_strings
note: String manipulation

View file

@ -0,0 +1,20 @@
Many languages have powerful and useful ('''binary safe''') [[wp:String (computer science)|string]] [[wp:Comparison of programming languages (string functions)|manipulation functions]], while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle ''binary'' strings (strings made of arbitrary bytes, i.e. ''byte strings'' according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the ''functions'' or ''abilities'' already provided by the language.
In particular the functions you need to create are:
* String creation and destruction (when needed and if there's no [[garbage collection]] or similar mechanism)
* String assignment
* String comparison
* String cloning and copying
* Check if a string is empty
* Append a byte to a string
* Extract a substring from a string
* Replace every occurrence of a byte (or a string) in a string with another string
* Join strings
<br>
Possible contexts of use: compression algorithms (like [[LZW compression]]), L-systems (manipulation of symbols), many more.
<br><br>

View file

@ -0,0 +1,2 @@
V x = Bytes(abc)
print(x[0])

View file

@ -0,0 +1,12 @@
;this code assumes that both DS and ES point to the correct segments.
cld
mov si,offset TestMessage
mov di,offset EmptyRam
mov cx,5 ;length of the source string, you'll need to either know this
;ahead of time or calculate it.
rep movsb
ret
;there is no buffer overflow protection built into these functions so be careful!
TestMessage byte "Hello"
EmptyRam byte 0,0,0,0,0

View file

@ -0,0 +1,11 @@
;this code assumes that ES points to the correct segment.
cld
mov di,offset TestMessage
mov al,'o' ;the byte we wish to check
mov cx,5 ;len(Test)
repnz scasb ;scan through the string and stop if a match is found.
;flags will be set accordingly
ret
TestMessage byte "Hello"

View file

@ -0,0 +1,14 @@
;this code assumes that both DS and ES point to the correct segments.
cld
mov si,offset foo
mov di,offset bar
mov cx,4 ;length of the shorter of the two.
repz cmpsb
; this will continue until the strings are different or CX = 0,
; whichever occurs first. If, after this, the zero flag is set and CX=0,
; the strings were the same
ret
foo byte "test"
bar byte "test"

View file

@ -0,0 +1,93 @@
# String creation #
STRING a,b,c,d,e,f,g,h,i,j,l,r;
a := "hello world";
print((a, new line));
# String destruction (for garbage collection) #
b := ();
BEGIN
LOC STRING lb := "hello earth"; # allocate off the LOC stack #
HEAP STRING hb := "hello moon"; # allocate out of the HEAP space #
~
END; # local variable "lb" has LOC stack space recovered at END #
# String assignment #
c := "a"+REPR 0+"b";
print (("string length c:", UPB c, new line));# ==> 3 #
# String comparison #
l := "ab"; r := "CD";
BOOL result;
FORMAT summary = $""""g""" is "b("","NOT ")"lexicographically "g" """g""""l$ ;
result := l < r OR l LT r; printf((summary, l, result, "less than", r));
result := l <= r OR l LE r # OR l ≤ r #; printf((summary, l, result, "less than or equal to", r));
result := l = r OR l EQ r; printf((summary, l, result, "equal to", r));
result := l /= r OR l NE r # OR l ≠ r #; printf((summary, l, result, "not equal to", r));
result := l >= r OR l GE r # OR l ≥ r #; printf((summary, l, result, "greater than or equal to", r));
result := l > r OR l GT r; printf((summary, l, result, "greater than", r));
# String cloning and copying #
e := f;
# Check if a string is empty #
IF g = "" THEN print(("g is empty", new line)) FI;
IF UPB g = 0 THEN print(("g is empty", new line)) FI;
# Append a byte to a string #
h +:= "A";
# Append a string to a string #
h +:= "BCD";
h PLUSAB "EFG";
# Prepend a string to a string - because STRING addition isn't communitive #
"789" +=: h;
"456" PLUSTO h;
print(("The result of prepends and appends: ", h, new line));
# Extract a substring from a string #
i := h[2:3];
print(("Substring 2:3 of ",h," is ",i, new line));
# Replace every occurrences of a byte (or a string) in a string with another string #
PROC replace = (STRING string, old, new, INT count)STRING: (
INT pos;
STRING tail := string, out;
TO count WHILE string in string(old, pos, tail) DO
out +:= tail[:pos-1]+new;
tail := tail[pos+UPB old:]
OD;
out+tail
);
j := replace("hello world", "world", "planet", max int);
print(("After replace string: ", j, new line));
INT offset = 7;
# Replace a character at an offset in the string #
j[offset] := "P";
print(("After replace 7th character: ", j, new line));
# Replace a substring at an offset in the string #
j[offset:offset+3] := "PlAN";
print(("After replace 7:10th characters: ", j, new line));
# Insert a string before an offset in the string #
j := j[:offset-1]+"INSERTED "+j[offset:];
print(("Insert string before 7th character: ", j, new line));
# Join strings #
a := "hel";
b := "lo w";
c := "orld";
d := a+b+c;
print(("a+b+c is ",d, new line));
# Pack a string into the target CPU's word #
BYTES word := bytes pack(d);
# Extract a CHAR from a CPU word #
print(("7th byte in CPU word is: ", offset ELEM word, new line))

View file

@ -0,0 +1,37 @@
#!/usr/bin/awk -f
BEGIN {
# string creation
a="123\0 abc ";
b="456\x09";
c="789";
printf("abc=<%s><%s><%s>\n",a,b,c);
# string comparison
printf("(a==b) is %i\n",a==b)
# string copying
A = a;
B = b;
C = c;
printf("ABC=<%s><%s><%s>\n",A,B,C);
# check if string is empty
if (length(a)==0) {
printf("string a is empty\n");
} else {
printf("string a is not empty\n");
}
# append a byte to a string
a=a"\x40";
printf("abc=<%s><%s><%s>\n",a,b,c);
# substring
e = substr(a,1,6);
printf("substr(a,1,6)=<%s>\n",e);
# join strings
d=a""b""c;
printf("d=<%s>\n",d);
}

View file

@ -0,0 +1,17 @@
declare
Data : Storage_Array (1..20); -- Data created
begin
Data := (others => 0); -- Assign all zeros
if Data = (1..10 => 0) then -- Compare with 10 zeros
declare
Copy : Storage_Array := Data; -- Copy Data
begin
if Data'Length = 0 then -- If empty
...
end if;
end;
end if;
... Data & 1 ... -- The result is Data with byte 1 appended
... 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

View file

@ -0,0 +1,3 @@
type Octet is mod 2**8;
for Octet'Size use 8;
type Octet_String is array (Positive range <>) of Octet;

View file

@ -0,0 +1,4 @@
with Interfaces; use Interfaces;
...
type Octet is new Interfaces.Unsigned_8;
type Octet_String is array (Positive range <>) of Octet;

View file

@ -0,0 +1,28 @@
REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM)
A$ = "STRING" : REM CREATION
A$ = "" : REM DESTRUCTION
PRINT FRE(0) : REM GARBAGE COLLECTION
REM STRING ASSIGNMENT
A$ = "STRING" : R$ = "DEUX"
REM STRING COMPARISON
PRINT A$ = B$; A$ <> B$; A$ < B$; A$ > B$; A$ <= B$; A$ >= B$
REM STRING CLONING AND COPYING
B$ = A$
REM CHECK IF A STRING IS EMPTY
PRINT LEN(A$) = 0
REM APPEND A BYTE TO A STRING
A$ = A$ + CHR$(0)
REM EXTRACT A SUBSTRING FROM A STRING
S$ = MID$(A$, 2, 3)
REM REPLACE EVERY OCCURRENCE OF A BYTE (OR A STRING) IN A STRING WITH ANOTHER STRING
S = LEN(S$) : R = LEN(R$) : A = LEN(A$) : IF A > S THEN B$ = "" : FOR I = 1 TO A : F = MID$(A$, I, S) = S$ : B$ = B$ + MID$(R$, 1, R * F) + MID$(A$, I, F = 0) : NEXT I : A$ = B$ : PRINT A$
REM JOIN STRINGS
J$ = A$ + STR$(42) + " PUDDLES " + B$ + CHR$(255) : REM USE +

View file

@ -0,0 +1,35 @@
; creation
x: "this is a string"
y: "this is another string"
z: "this is a string"
; comparison
if x = z -> print "x is z"
; assignment
z: "now this is another string too"
; copying reference
y: z
; copying value
y: new z
; check if empty
if? empty? x -> print "empty"
else -> print "not empty"
; append a string
'x ++ "!"
print x
; substrings
print slice x 5 8
; join strings
z: x ++ y
print z
; replace occurrences of substring
print replace z "t" "T"

View file

@ -0,0 +1,15 @@
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
IF A$ = "" THEN PRINT "String is empty" : REM Check if empty
A$ += CHR$(128) : REM Append a byte
S$ = MID$(A$, S%, L%) : REM Extract a substring
C$ = A$ + B$ : REM Join strings
REM To replace every occurrence of a byte:
old$ = CHR$(1)
new$ = CHR$(5)
REPEAT
I% = INSTR(A$, old$)
IF I% MID$(A$, I%, 1) = new$
UNTIL I% = 0

View file

@ -0,0 +1 @@
name ""

View file

@ -0,0 +1 @@
n + @

View file

@ -0,0 +1 @@
10255 + @

View file

@ -0,0 +1 @@
name 0

View file

@ -0,0 +1 @@
name "value"

View file

@ -0,0 +1 @@
name1 name2

View file

@ -0,0 +1,2 @@
name1 "example"
name2 name1

View file

@ -0,0 +1 @@
0=string

View file

@ -0,0 +1,3 @@
string "example"
byte @
string byte

View file

@ -0,0 +1 @@
3¯5"The quick brown fox runs..."

View file

@ -0,0 +1 @@
"string1""string2"

View file

@ -0,0 +1,64 @@
#include <iomanip>
#include <iostream>
using namespace std;
string replaceFirst(string &s, const string &target, const string &replace) {
auto pos = s.find(target);
if (pos == string::npos) return s;
return s.replace(pos, target.length(), replace);
}
int main() {
// string creation
string x = "hello world";
// reassign string (no garbage collection)
x = "";
// string assignment with a null byte
x = "ab\0";
cout << x << '\n';
cout << x.length() << '\n';
// string comparison
if (x == "hello") {
cout << "equal\n";
} else {
cout << "not equal\n";
}
if (x < "bc") {
cout << "x is lexigraphically less than 'bc'\n";
}
// string cloning
auto y = x;
cout << boolalpha << (x == y) << '\n';
cout << boolalpha << (&x == &y) << '\n';
// check if empty
string empty = "";
if (empty.empty()) {
cout << "String is empty\n";
}
// append a byte
x = "helloworld";
x += (char)83;
cout << x << '\n';
// substring
auto slice = x.substr(5, 5);
cout << slice << '\n';
// replace bytes
auto greeting = replaceFirst(x, "worldS", "");
cout << greeting << '\n';
// join strings
auto join = greeting + ' ' + slice;
cout << join << '\n';
return 0;
}

View file

@ -0,0 +1,65 @@
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);
}
}

View file

@ -0,0 +1,138 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct str_t {
size_t len, alloc;
unsigned char *s;
} bstr_t, *bstr;
#define str_len(s) ((s)->len)
bstr str_new(size_t len)
{
bstr s = malloc(sizeof(bstr_t));
if (len < 8) len = 8;
s->alloc = len;
s->s = malloc(len);
s->len = 0;
return s;
}
void str_extend(bstr s)
{
size_t ns = s->alloc * 2;
if (ns - s->alloc > 1024) ns = s->alloc + 1024;
s->s = realloc(s->s, ns);
s->alloc = ns;
}
void str_del(bstr s)
{
free(s->s), free(s);
}
int str_cmp(bstr l, bstr r)
{
int res, len = l->len;
if (len > r->len) len = r->len;
if ((res = memcmp(l->s, r->s, len))) return res;
return l->len > r->len ? 1 : -1;
}
bstr str_dup(bstr src)
{
bstr x = str_new(src->len);
memcpy(x->s, src->s, src->len);
x->len = src->len;
return x;
}
bstr str_from_chars(const char *t)
{
if (!t) return str_new(0);
size_t l = strlen(t);
bstr x = str_new(l + 1);
x->len = l;
memcpy(x->s, t, l);
return x;
}
void str_append(bstr s, unsigned char b)
{
if (s->len >= s->alloc) str_extend(s);
s->s[s->len++] = b;
}
bstr str_substr(bstr s, int from, int to)
{
if (!to) to = s->len;
if (from < 0) from += s->len;
if (from < 0 || from >= s->len)
return 0;
if (to < from) to = from + 1;
bstr x = str_new(to - from);
x->len = to - from;
memcpy(x->s, s->s + from, x->len);
return x;
}
bstr str_cat(bstr s, bstr s2)
{
while (s->alloc < s->len + s2->len) str_extend(s);
memcpy(s->s + s->len, s2->s, s2->len);
s->len += s2->len;
return s;
}
void str_swap(bstr a, bstr b)
{
size_t tz;
unsigned char *ts;
tz = a->alloc; a->alloc = b->alloc; b->alloc = tz;
tz = a->len; a->len = b->len; b->len = tz;
ts = a->s; a->s = b->s; b->s = ts;
}
bstr str_subst(bstr tgt, bstr pat, bstr repl)
{
bstr tmp = str_new(0);
int i;
for (i = 0; i + pat->len <= tgt->len;) {
if (memcmp(tgt->s + i, pat->s, pat->len)) {
str_append(tmp, tgt->s[i]);
i++;
} else {
str_cat(tmp, repl);
i += pat->len;
if (!pat->len) str_append(tmp, tgt->s[i++]);
}
}
while (i < tgt->len) str_append(tmp, tgt->s[i++]);
str_swap(tmp, tgt);
str_del(tmp);
return tgt;
}
void str_set(bstr dest, bstr src)
{
while (dest->len < src->len) str_extend(dest);
memcpy(dest->s, src->s, src->len);
dest->len = src->len;
}
int main()
{
bstr s = str_from_chars("aaaaHaaaaaFaaaaHa");
bstr s2 = str_from_chars("___.");
bstr s3 = str_from_chars("");
str_subst(s, s3, s2);
printf("%.*s\n", s->len, s->s);
str_del(s);
str_del(s2);
str_del(s3);
return 0;
}

View file

@ -0,0 +1,2 @@
"string"
(coerce '(#\s #\t #\r #\i #\n #\g) 'string)

View file

@ -0,0 +1 @@
(defvar *string* "string")

View file

@ -0,0 +1 @@
(equal "string" "string")

View file

@ -0,0 +1 @@
(copy-seq "string")

View file

@ -0,0 +1,2 @@
(defun string-empty-p (string)
(zerop (length string)))

View file

@ -0,0 +1 @@
(concatenate 'string "string" "b")

View file

@ -0,0 +1,2 @@
(subseq "string" 2 6)
"ring"

View file

@ -0,0 +1,64 @@
MODULE NpctBinaryString;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
str: ARRAY 256 OF CHAR;
pStr,pAux: POINTER TO ARRAY OF CHAR;
b: BYTE;
pIni: INTEGER;
BEGIN
(* String creation, on heap *)
NEW(pStr,256); (* Garbage collectable *)
NEW(pAux,256);
(* String assingment *)
pStr^ := "This is a string on a heap";
pAux^ := "This is a string on a heap";
str := "This is other string";
(* String comparision *)
StdLog.String("pStr = str:> ");StdLog.Bool(pStr$ = str$);StdLog.Ln;
StdLog.String("pStr = pAux:> ");StdLog.Bool(pStr$ = pAux$);StdLog.Ln;
(* String cloning and copying *)
NEW(pAux,LEN(pStr$) + 1);pAux^ := pStr$;
(* Check if a string is empty *)
(* version 1 *)
pAux^ := "";
StdLog.String("is empty pAux?(1):> ");StdLog.Bool(pAux$ = "");StdLog.Ln;
(* version 2 *)
pAux[0] := 0X;
StdLog.String("is empty pAux?(2):> ");StdLog.Bool(pAux$ = "");StdLog.Ln;
(* version 3 *)
pAux[0] := 0X;
StdLog.String("is empty pAux?(3):> ");StdLog.Bool(pAux[0] = 0X);StdLog.Ln;
(* version 4 *)
pAux^ := "";
StdLog.String("is empty pAux?(4):> ");StdLog.Bool(pAux[0] = 0X);StdLog.Ln;
(* Append a byte to a string *)
NEW(pAux,256);pAux^ := "BBBBBBBBBBBBBBBBBBBBB";
b := 65;pAux[LEN(pAux$)] := CHR(b);
StdLog.String("pAux:> ");StdLog.String(pAux);StdLog.Ln;
(* Extract a substring from a string *)
Strings.Extract(pStr,0,16,pAux);
StdLog.String("pAux:> ");StdLog.String(pAux);StdLog.Ln;
(* Replace a every ocurrence of a string with another string *)
pAux^ := "a"; (* Pattern *)
Strings.Find(pStr,pAux,0,pIni);
WHILE pIni > 0 DO
Strings.Replace(pStr,pIni,LEN(pAux$),"one");
Strings.Find(pStr,pAux,pIni + 1,pIni);
END;
StdLog.String("pStr:> ");StdLog.String(pStr);StdLog.Ln;
(* Join strings *)
pStr^ := "First string";pAux^ := "Second String";
str := pStr$ + "." + pAux$;
StdLog.String("pStr + '.' + pAux:>");StdLog.String(str);StdLog.Ln
END Do;
END NpctBinaryString.

View file

@ -0,0 +1,45 @@
void main() /*@safe*/ {
import std.array: empty, replace;
import std.string: representation, assumeUTF;
// String creation (destruction is usually handled by
// the garbage collector).
ubyte[] str1;
// String assignments.
str1 = "blah".dup.representation;
// Hex string, same as "\x00\xFB\xCD\x32\xFD\x0A"
// whitespace and newlines are ignored.
str1 = cast(ubyte[])x"00 FBCD 32FD 0A";
// String comparison.
ubyte[] str2;
if (str1 == str2) {} // Strings equal.
// String cloning and copying.
str2 = str1.dup; // Copy entire string or array.
// Check if a string is empty
if (str1.empty) {} // String empty.
if (str1.length) {} // String not empty.
if (!str1.length) {} // String empty.
// Append a ubyte to a string.
str1 ~= x"0A";
str1 ~= 'a';
// Extract a substring from a string.
str1 = "blork".dup.representation;
// This takes off the first and last bytes and
// assigns them to the new ubyte string.
// This is just a light slice, no string data copied.
ubyte[] substr = str1[1 .. $ - 1];
// Replace every occurrence of a ubyte (or a string)
// in a string with another string.
str1 = "blah".dup.representation;
replace(str1.assumeUTF, "la", "al");
// Join two strings.
ubyte[] str3 = str1 ~ str2;
}

View file

@ -0,0 +1,74 @@
program Binary_strings;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
x : string;
c : TArray<Byte>;
objecty,
y : string;
empty : string;
nullString : string;
whitespace,
slice,
greeting,
join : string;
begin
//string creation
x:= String.create(['1','2','3']);
x:= String.create('*',8);
x := 'hello world';
//# string assignment with a hex byte
x := 'ab'#10;
writeln(x);
writeln(x.Length); // 3
//# string comparison
if x = 'hello' then
writeln('equal')
else
writeln('not equal');
if x.CompareTo('bc') = -1 then
writeln('x is lexicographically less than "bc"');
//# string cloning
y := x; // string is not object is delphi (are imutables)
writeln(x = y); //same as string.equals
writeln(x.Equals(y)); //it overrides object.Equals
//# check if empty
// Strings can't be null (nil), just Pchar can be
// IsNullOrEmpty and IsNullOrWhiteSpace, check only for
// Empty and Whitespace respectively.
empty := '';
whitespace := ' ';
if (empty = string.Empty) and
string.IsNullOrEmpty(empty) and
string.IsNullOrWhiteSpace(empty) and
string.IsNullOrWhiteSpace(whitespace) then
writeln('Strings are empty or whitespace');
//# append a byte
x := 'helloworld';
x := x + Chr(83);
// x := x + #83; // the same of above line
writeln(x);
//# substring
slice := x.Substring(5, 5);
writeln(slice);
//# replace bytes
greeting := x.Replace('worldS', '');
writeln(greeting);
//# join strings
join := greeting + ' ' + slice;
writeln(join);
Readln;
end.

View file

@ -0,0 +1,2 @@
? def int8 := <type:java.lang.Byte>
# value: int8

View file

@ -0,0 +1,8 @@
? def bstr := [].diverge(int8)
# value: [].diverge()
? def bstr1 := [1,2,3].diverge(int8)
# value: [1, 2, 3].diverge()
? def bstr2 := [-0x7F,0x2,0x3].diverge(int8)
# value: [-127, 2, 3].diverge()

View file

@ -0,0 +1,2 @@
? bstr1.snapshot() < bstr2.snapshot()
# value: false

View file

@ -0,0 +1,5 @@
? bstr1.size().isZero()
# value: false
? bstr.size().isZero()
# value: true

View file

@ -0,0 +1,3 @@
? bstr.push(0)
? bstr
# value: [0].diverge()

View file

@ -0,0 +1,6 @@
? bstr1(1, 2)
# value: [2]
? bstr.replace(0, bstr.size(), bstr2, 1, 3)
? bstr
# value: [2, 3].diverge()

View file

@ -0,0 +1,3 @@
? for i => byte ? (byte == 2) in bstr2 { bstr2[i] := -1 }
? bstr2
# value: [-127, -1, 3].diverge()

View file

@ -0,0 +1,3 @@
? bstr1.append(bstr2)
? bstr1
# value: [1, 2, 3, -127, 2, 3].diverge()

View file

@ -0,0 +1,71 @@
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}
|
);
}
}

View file

@ -0,0 +1,55 @@
# String creation
x = "hello world"
# String destruction
x = nil
# String assignment with a null byte
x = "a\0b"
IO.inspect x #=> <<97, 0, 98>>
IO.puts String.length(x) #=> 3
# string comparison
if x == "hello" do
IO.puts "equal"
else
IO.puts "not equal" #=> not equal
end
y = "bc"
if x < y do
IO.puts "#{x} is lexicographically less than #{y}" #=> a b is lexicographically less than bc
end
# string cloning
xx = x
IO.puts x == xx #=> true same length and content)
# check if empty
if x=="" do
IO.puts "is empty"
end
if String.length(x)==0 do
IO.puts "is empty"
end
# append a byte
IO.puts x <> "\07" #=> a b 7
IO.inspect x <> "\07" #=> <<97, 0, 98, 0, 55>>
# substring
IO.puts String.slice("elixir", 1..3) #=> lix
IO.puts String.slice("elixir", 2, 3) #=> ixi
# replace bytes
IO.puts String.replace("a,b,c", ",", "-") #=> a-b-c
# string interpolation
a = "abc"
n = 100
IO.puts "#{a} : #{n}" #=> abc : 100
# join strings
a = "hel"
b = "lo w"
c = "orld"
IO.puts a <> b <> c #=> hello world

View file

@ -0,0 +1,49 @@
-module(binary_string).
-compile([export_all]).
%% Erlang has very easy handling of binary strings. Using
%% binary/bitstring syntax the various task features will be
%% demonstrated.
%% Erlang has GC so destruction is not shown.
test() ->
Binary = <<0,1,1,2,3,5,8,13>>, % binaries can be created directly
io:format("Creation: ~p~n",[Binary]),
Copy = binary:copy(Binary), % They can also be copied
io:format("Copy: ~p~n",[Copy]),
Compared = Binary =:= Copy, % They can be compared directly
io:format("Equal: ~p = ~p ? ~p~n",[Binary,Copy,Compared]),
Empty1 = size(Binary) =:= 0, % The empty binary would have size 0
io:format("Empty: ~p ? ~p~n",[Binary,Empty1]),
Empty2 = size(<<>>) =:= 0, % The empty binary would have size 0
io:format("Empty: ~p ? ~p~n",[<<>>,Empty2]),
Substring = binary:part(Binary,3,3),
io:format("Substring: ~p [~b..~b] => ~p~n",[Binary,3,5,Substring]),
Replace = binary:replace(Binary,[<<1>>],<<42>>,[global]),
io:format("Replacement: ~p~n",[Replace]),
Append = <<Binary/binary,21>>,
io:format("Append: ~p~n",[Append]),
Join = <<Binary/binary,<<21,34,55>>/binary>>,
io:format("Join: ~p~n",[Join]).
%% Since the task also asks that we show how these can be reproduced
%% rather than just using BIFs, the following are some example
%% recursive functions reimplementing some of the above.
%% Empty string
is_empty(<<>>) ->
true;
is_empty(_) ->
false.
%% Replacement:
replace(Binary,Value,Replacement) ->
replace(Binary,Value,Replacement,<<>>).
replace(<<>>,_,_,Acc) ->
Acc;
replace(<<Value,Rest/binary>>,Value,Replacement,Acc) ->
replace(Rest,Value,Replacement,<< Acc/binary, Replacement >>);
replace(<<Keep,Rest/binary>>,Value,Replacement,Acc) ->
replace(Rest,Value,Replacement,<< Acc/binary, Keep >>).

View file

@ -0,0 +1,10 @@
215> binary_string:test().
Creation: <<0,1,1,2,3,5,8,13>>
Copy: <<0,1,1,2,3,5,8,13>>
Equal: <<0,1,1,2,3,5,8,13>> = <<0,1,1,2,3,5,8,13>> ? true
Empty: <<0,1,1,2,3,5,8,13>> ? false
Empty: <<>> ? true
Substring: <<0,1,1,2,3,5,8,13>> [3..5] => <<2,3,5>>
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>>

View file

@ -0,0 +1 @@
"Hello, byte-array!" utf8 encode .

View file

@ -0,0 +1 @@
B{ 147 250 150 123 } shift-jis decode .

View file

@ -0,0 +1,96 @@
\ Rosetta Code Binary Strings Demo in Forth
\ Portions of this code are found at http://forth.sourceforge.net/mirror/toolbelt-ext/index.html
\ String words created in this code:
\ STR< STR> STR= COMPARESTR SUBSTR STRPAD CLEARSTR
\ ="" =" STRING: MAXLEN REPLACE-CHAR COPYSTR WRITESTR
\ ," APPEND-CHAR STRING, PLACE CONCAT APPEND C+! ENDSTR
\ COUNT STRLEN
: STRLEN ( addr -- length) c@ ; \ alias the "character fetch" operator
: COUNT ( addr -- addr+1 length) \ Standard word. Shown for explanation
dup strlen swap 1+ swap ; \ returns the address+1 and the length byte on the stack
: ENDSTR ( str -- addr) \ calculate the address at the end of a string
COUNT + ;
: C+! ( n addr -- ) \ primitive: increment a byte at addr by n
DUP C@ ROT + SWAP C! ;
: APPEND ( addr1 length addr2 -- ) \ Append addr1 length to addr2
2dup 2>r endstr swap move 2r> c+! ;
: CONCAT ( string1 string2 -- ) \ concatenate counted string1 to counted string2
>r COUNT R> APPEND ;
: PLACE ( addr1 len addr2 -- ) \ addr1 and length, placed at addr2 as counted string
2dup 2>r char+ swap move 2r> c! ;
: STRING, ( addr len -- ) \ compile a string at the next available memory (called 'HERE')
here over char+ allot place ;
: APPEND-CHAR ( char string -- ) \ append char to string
dup >r count dup 1+ r> c! + c! ;
: ," [CHAR] " PARSE STRING, ; \ Parse input stream until '"' and compile into memory
: WRITESTR ( string -- ) \ output a counted string with a carriage return
count type CR ;
: COPYSTR ( string1 string3 -- ) \ String cloning and copying COPYSTR
>r count r> PLACE ;
: REPLACE-CHAR ( char1 char2 string -- ) \ replace all char2 with char1 in string
count \ get string's address and length
BOUNDS \ calc start and end addr of string for do-loop
DO \ do a loop from start address to end address
I C@ OVER = \ fetch the char at loop index compare to CHAR2
IF
OVER I C! \ if its equal, store CHAR1 into the index address
THEN
LOOP
2drop ; \ drop the chars off the stack
256 constant maxlen \ max size of byte counted string in this example
: string: CREATE maxlen ALLOT ; \ simple string variable constructor
: =" ( string -- ) \ String variable assignment operator (compile time only)
[char] " PARSE ROT PLACE ;
: ="" ( string -- ) 0 swap c! ; \ empty a string, set count to zero
: clearstr ( string -- ) \ erase a string variables contents, fill with 0
maxlen erase ;
string: strpad \ general purpose storage buffer
: substr ( string1 start length -- strpad) \ Extract a substring of string and return an output string
>r >r \ push start,length
count \ compute addr,len
r> 1- /string \ pop start, subtract 1, cut string
drop r> \ drop existing length, pop new length
strpad place \ place new stack string in strpad
strpad ; \ return address of strpad
\ COMPARE takes the 4 inputs from the stack (addr1 len1 addr2 len2 )
\ and returns a flag for equal (0) , less-than (1) or greater-than (-1) on the stack
: comparestr ( string1 string2 -- flag) \ adapt for use with counted strings
count rot count compare ;
\ now it's simple to make new operators
: STR= ( string1 string2 -- flag)
comparestr 0= ;
: STR> ( string1 string2 -- flag)
comparestr -1 = ;
: STR< ( string1 string2 -- flag)
comparestr 1 = ;

View file

@ -0,0 +1,125 @@
\ Rosetta Code Binary String tasks Console Tests
\ 1. String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
\ RAW Forth can manually create a binary string with the C, operator.
\ C, takes a byte off the stack and writes it into the next available memory address
\ then increments the Forth internal memory pointer by 1 byte.
\ 'binary_string' drops it's address on the stack. Nothing more. (ie: pointer to the string)
HEX ok
create binary_string 9 c, 1 c, 2 c, 3 c, 4 c, 5 c,
0A c, 0B c, 0C c, 0FF c, \ 1st byte is length
ok
\ test what we created using the DUMP utility
binary_string count dump
25EC:7365 01 02 03 04 05 0A 0B 0C FF 04 44 55 4D 50 00 20 ..........DUMP.
ok
\ Alternatively we can create static string variables using our constructor
string: buffer1 ok
string: buffer2 ok
DECIMAL ok
\ 2. String assignment
\ create string constants with assignments(static, counted strings) ok
create string1 ," Now is the time for all good men to come to the aid"
create string2 ," Right now!" ok
\ assign text to string variables with syntacic sugar
buffer1 =" This text will go into the memory allocated for buffer1" ok
buffer2 ="" ok
\ or use S" and PLACE
S" The rain in Spain..." buffer2 PLACE ok
\ Test the assignments
string2 writestr Right now!
ok
string1 writestr Now is the time for all good men to come to the aid
ok
buffer1 writestr This text will go into the memory allocated for buffer1
ok
buffer2 writestr The rain in Spain...
ok
\ destroy string contents. Fill string with zero
buffer1 clearstr ok
buffer1 40 dump
25EC:7370 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
25EC:7380 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
25EC:7390 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
ok
\ 3. String comparison. ( the '.' prints the top of the stack in these examples)
buffer1 =" ABCDEFG" ok
buffer2 =" ABCDEFG" ok
buffer1 buffer2 STR= . ( should be -1, TRUE flag) -1 ok
string1 buffer1 str> . ( should be 0) 0 ok
string1 buffer1 str< . ( should be -1) -1 ok
\ 4. String cloning and copying
string1 buffer1 COPYSTR ok
string1 writestr Now is the time for all good men to come to the aid ok
buffer1 writestr Now is the time for all good men to come to the aid ok
\ 5. Check if a string is empty
buffer1 len . 55 ok
buffer1 ="" \ assign null string ok
buffer1 len . 0 ok
\ 6. Append a byte to a string
buffer2 =" Append this" ok
buffer2 writestr Append this
ok
char ! buffer2 APPEND-CHAR ok
buffer2 writestr Append this!
ok
hex ok
0A buffer2 APPEND-CHAR \ append a raw carriage return ok
0D buffer2 APPEND-CHAR \ append a raw line-feed ok
ok
buffer2 writestr Append this!
ok
\ we see the extra line before OK so Appending binary chars worked
decimal ok
\ 7. Extract a substring from a string. Result placed in a temp buffer automagically
string1 writestr Now is the time for all good men to come to the aid ok
string1 5 11 substr writestr is the time ok
\ 8. Replace every occurrence of a byte (or a string) in a string with another string
\ BL is a system constant for "Blank" ie the space character (HEX 020)
buffer1 =" This*string*is*full*of*stars*" ok
ok
BL char * buffer1 REPLACE-CHAR ok
buffer1 writestr This string is full of stars
ok
\ 9. Join strings
buffer1 =" James " ok
buffer2 =" Alexander" ok
buffer2 buffer1 CONCAT ok
ok
buffer1 writestr James Alexander
ok

View file

@ -0,0 +1,39 @@
Dim As String cad, cad2
'creación de cadenas
cad = "¡Hola Mundo!"
'destrucción de cadenas: no es necesario debido a la recolección de basura
cad = ""
'clonación/copia de cadena
cad2 = cad
'comparación de cadenas
If cad = cad2 Then Print "Las cadenas son iguales"
'comprobar si está vacío
If cad = "" Then Print "Cadena vac¡a"
'agregar un byte
cad += Chr(33)
'extraer una subcadena
cad2 = Mid(cad, 1, 5)
'reemplazar bytes
cad2 = "­Hola mundo!"
For i As Integer = 1 To Len(cad2)
If Mid(cad2,i,1) = "l" Then
cad2 = Left(cad2,i-1) + "L" + Mid(cad2,i+1)
End If
Next
Print cad2
'unir cadenas
cad = "Hasta " + "pronto " + "de momento."
'imprimir caracteres 2 a 4 de una cadena (una subcadena)
For i As Integer = 2 To 4
Print Chr(cad[i])
Next i
Sleep

View file

@ -0,0 +1,48 @@
// 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

View file

@ -0,0 +1,47 @@
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

View file

@ -0,0 +1,13 @@
10 ' SAVE"BINSTR", A
20 ' This program does string manipulation
30 A$ = "One value" ' String creation
40 A$ = "": PRINT FRE("") ' String destruction
50 A$ = "One value": B$ = "Other value" ' String assignment
60 PRINT A$ = B$; A$ <> B$; A$ < B$; A$ > B$; A$ <= B$; A$ >= B$' String comparison
70 B$ = A$ ' String cloning and copying
80 PRINT A$ = ""' Check if a string is empty
90 A$ = A$ + "!": PRINT A$' Append a byte to a string
100 PRINT MID$(A$, 5, 5); MID$(A$, 4, 1); LEFT$(A$, 3); RIGHT$(A$, 1)' Extract a substring from a string
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

View file

@ -0,0 +1,85 @@
package main
import (
"bytes"
"fmt"
)
// Strings in Go allow arbitrary bytes. They are implemented basically as
// immutable byte slices and syntactic sugar. This program shows functions
// required by the task on byte slices, thus it mostly highlights what
// happens behind the syntactic sugar. The program does not attempt to
// reproduce the immutability property of strings, as that does not seem
// to be the intent of the task.
func main() {
// Task point: String creation and destruction.
// Strings are most often constructed from literals as in s := "binary"
// With byte slices,
b := []byte{'b', 'i', 'n', 'a', 'r', 'y'}
fmt.Println(b) // output shows numeric form of bytes.
// Go is garbage collected. There are no destruction operations.
// Task point: String assignment.
// t = s assigns strings. Since strings are immutable, it is irrelevant
// whether the string is copied or not.
// With byte slices, the same works,
var c []byte
c = b
fmt.Println(c)
// Task point: String comparison.
// operators <, <=, ==, >=, and > work directly on strings comparing them
// by lexicographic order.
// With byte slices, there are standard library functions, bytes.Equal
// and bytes.Compare.
fmt.Println(bytes.Equal(b, c)) // prints true
// Task point: String cloning and copying.
// The immutable property of Go strings makes cloning and copying
// meaningless for strings.
// With byte slices though, it is relevant. The assignment c = b shown
// above does a reference copy, leaving both c and b based on the same
// underlying data. To clone or copy the underlying data,
d := make([]byte, len(b)) // allocate new space
copy(d, b) // copy the data
// The data can be manipulated independently now:
d[1] = 'a'
d[4] = 'n'
fmt.Println(string(b)) // convert to string for readable output
fmt.Println(string(d))
// Task point: Check if a string is empty.
// Most typical for strings is s == "", but len(s) == 0 works too.
// For byte slices, "" does not work, len(b) == 0 is correct.
fmt.Println(len(b) == 0)
// Task point: Append a byte to a string.
// The language does not provide a way to do this directly with strings.
// Instead, the byte must be converted to a one-byte string first, as in,
// s += string('z')
// For byte slices, the language provides the append function,
z := append(b, 'z')
fmt.Printf("%s\n", z) // another way to get readable output
// Task point: Extract a substring from a string.
// Slicing syntax is the for both strings and slices.
sub := b[1:3]
fmt.Println(string(sub))
// Task point: Replace every occurrence of a byte (or a string)
// in a string with another string.
// Go supports this with similar library functions for strings and
// byte slices. Strings: t = strings.Replace(s, "n", "m", -1).
// The byte slice equivalent returns a modified copy, leaving the
// original byte slice untouched,
f := bytes.Replace(d, []byte{'n'}, []byte{'m'}, -1)
fmt.Printf("%s -> %s\n", d, f)
// Task point: Join strings.
// Using slicing syntax again, with strings,
// rem := s[:1] + s[3:] leaves rem == "bary".
// Only the concatenation of the parts is different with byte slices,
rem := append(append([]byte{}, b[:1]...), b[3:]...)
fmt.Println(string(rem))
}

View file

@ -0,0 +1,119 @@
import java.nio.charset.StandardCharsets
class MutableByteString {
private byte[] bytes
private int length
MutableByteString(byte... bytes) {
setInternal(bytes)
}
int length() {
return length
}
boolean isEmpty() {
return length == 0
}
byte get(int index) {
return bytes[check(index)]
}
void set(byte[] bytes) {
setInternal(bytes)
}
void set(int index, byte b) {
bytes[check(index)] = b
}
void append(byte b) {
if (length >= bytes.length) {
int len = 2 * bytes.length
if (len < 0) {
len = Integer.MAX_VALUE
}
bytes = Arrays.copyOf(bytes, len)
}
bytes[length] = b
length++
}
MutableByteString substring(int from, int to) {
return new MutableByteString(Arrays.copyOfRange(bytes, from, to))
}
void replace(byte[] from, byte[] to) {
ByteArrayOutputStream copy = new ByteArrayOutputStream()
if (from.length == 0) {
for (byte b : bytes) {
copy.write(to, 0, to.length)
copy.write(b)
}
copy.write(to, 0, to.length)
} else {
for (int i = 0; i < length; i++) {
if (regionEqualsImpl(i, from)) {
copy.write(to, 0, to.length)
i += from.length - 1
} else {
copy.write(bytes[i])
}
}
}
set(copy.toByteArray())
}
boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) {
if (Math.max(offset, otherOffset) + len < 0) {
return false
}
if (offset + len > length || otherOffset + len > other.length()) {
return false
}
for (int i = 0; i < len; i++) {
if (bytes[offset + i] != other.get(otherOffset + i)) {
return false
}
}
return true
}
String toHexString() {
char[] hex = new char[2 * length]
for (int i = 0; i < length; i++) {
hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F)
hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F)
}
return new String(hex)
}
String toStringUtf8() {
return new String(bytes, 0, length, StandardCharsets.UTF_8)
}
private void setInternal(byte[] bytes) {
this.bytes = bytes.clone()
this.length = bytes.length
}
private boolean regionEqualsImpl(int offset, byte[] other) {
int len = other.length
if (offset < 0 || offset + len < 0)
return false
if (offset + len > length)
return false
for (int i = 0; i < len; i++) {
if (bytes[offset + i] != other[i])
return false
}
return true
}
private int check(int index) {
if (index < 0 || index >= length)
throw new IndexOutOfBoundsException(String.valueOf(index))
return index
}
}

View file

@ -0,0 +1,59 @@
import org.testng.Assert
import org.testng.annotations.Test
import java.nio.charset.StandardCharsets
class MutableByteStringTest {
@Test
void replaceEmpty() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8))
str.replace([] as byte[], ['-' as char] as byte[])
Assert.assertEquals(str.toStringUtf8(), "-h-e-l-l-o-")
}
@Test
void replaceMultiple() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8))
str.replace(['l' as char] as byte[], ['1' as char, '2' as char, '3' as char] as byte[])
Assert.assertEquals(str.toStringUtf8(), "he123123o")
}
@Test
void toHexString() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8))
Assert.assertEquals(str.toHexString(), "68656c6c6f")
}
@Test
void append() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8))
str.append((',' as char) as byte)
str.append((' ' as char) as byte)
str.append(('w' as char) as byte)
str.append(('o' as char) as byte)
str.append(('r' as char) as byte)
str.append(('l' as char) as byte)
str.append(('d' as char) as byte)
Assert.assertEquals(str.toStringUtf8(), "hello, world")
}
@Test
void substring() {
MutableByteString str = new MutableByteString("hello, world".getBytes(StandardCharsets.UTF_8))
Assert.assertEquals(str.substring(0, 5).toStringUtf8(), "hello")
Assert.assertEquals(str.substring(7, 12).toStringUtf8(), "world")
}
@Test
void regionEquals(){
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8))
Assert.assertTrue(str.regionEquals(0, new MutableByteString(['h' as char] as byte[]), 0, 1))
Assert.assertFalse(str.regionEquals(0, new MutableByteString(['h' as char] as byte[]), 0, 2))
}
}

View file

@ -0,0 +1,9 @@
import Text.Regex
{- The above import is needed only for the last function.
It is used there purely for readability and conciseness -}
{- Assigning a string to a 'variable'.
We're being explicit about it just for show.
Haskell would be able to figure out the type
of "world" -}
string = "world" :: String

View file

@ -0,0 +1,8 @@
{- Comparing two given strings and
returning a boolean result using a
simple conditional -}
strCompare :: String -> String -> Bool
strCompare x y =
if x == y
then True
else False

View file

@ -0,0 +1,8 @@
{- As strings are equivalent to lists
of characters in Haskell, test and
see if the given string is an empty list -}
strIsEmpty :: String -> Bool
strIsEmpty x =
if x == []
then True
else False

View file

@ -0,0 +1,8 @@
{- This is the most obvious way to
append strings, using the built-in
(++) concatenation operator
Note the same would work to join
any two strings (as 'variables' or
as typed strings -}
strAppend :: String -> String -> String
strAppend x y = x ++ y

View file

@ -0,0 +1,4 @@
{- Take the specified number of characters
from the given string -}
strExtract :: Int -> String -> String
strExtract x s = take x s

View file

@ -0,0 +1,4 @@
{- 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)

View file

@ -0,0 +1,5 @@
{- 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

View file

@ -0,0 +1,13 @@
100 RANDOMIZE
110 REM create two strings
120 LET S$="Hello":LET T$="Bob"
130 REM choose any random character
140 LET C=(RND(127)+32)
150 REM add the character to the string
160 LET S$=S$&CHR$(C)
170 REM check if the string is empty
180 IF S$="" THEN PRINT "String is empty"
190 REM compare two strings
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)

View file

@ -0,0 +1,14 @@
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)
v := s # assignment
s == t # expression s equals t
s << t # expression s less than t
s <<= t # expression s less than or equal to t
v := s # strings are immutable, no copying or cloning are needed
s == "" # equal empty string
*s = 0 # string length is zero
s ||:= "a" # append a byte "a" to s via concatenation
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

View file

@ -0,0 +1,16 @@
procedure replace(s1, s2, s3) #: string replacement
local result, i
result := ""
i := *s2
if i = 0 then fail # would loop on empty string
s1 ? {
while result ||:= tab(find(s2)) do {
result ||:= s3
move(i)
}
return result || tab(0)
}
end

View file

@ -0,0 +1 @@
name=: ''

View file

@ -0,0 +1 @@
'string1','string2'

View file

@ -0,0 +1 @@
n{a.

View file

@ -0,0 +1 @@
1 0 255{a.

View file

@ -0,0 +1 @@
name=: 0

View file

@ -0,0 +1 @@
name=: 'value'

View file

@ -0,0 +1 @@
name1 -: name2

View file

@ -0,0 +1,2 @@
name1=: 'example'
name2=: name1

View file

@ -0,0 +1 @@
0=#string

View file

@ -0,0 +1,3 @@
string=: 'example'
byte=: DEL
string=: string,byte

View file

@ -0,0 +1 @@
3{.5}.'The quick brown fox runs...'

View file

@ -0,0 +1,2 @@
require 'strings'
'The quick brown fox runs...' rplc ' ';' !!! '

View file

@ -0,0 +1,118 @@
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class MutableByteString {
private byte[] bytes;
private int length;
public MutableByteString(byte... bytes) {
setInternal(bytes);
}
public int length() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public byte get(int index) {
return bytes[check(index)];
}
public void set(byte[] bytes) {
setInternal(bytes);
}
public void set(int index, byte b) {
bytes[check(index)] = b;
}
public void append(byte b) {
if (length >= bytes.length) {
int len = 2 * bytes.length;
if (len < 0)
len = Integer.MAX_VALUE;
bytes = Arrays.copyOf(bytes, len);
}
bytes[length] = b;
length++;
}
public MutableByteString substring(int from, int to) {
return new MutableByteString(Arrays.copyOfRange(bytes, from, to));
}
public void replace(byte[] from, byte[] to) {
ByteArrayOutputStream copy = new ByteArrayOutputStream();
if (from.length == 0) {
for (byte b : bytes) {
copy.write(to, 0, to.length);
copy.write(b);
}
copy.write(to, 0, to.length);
} else {
for (int i = 0; i < length; i++) {
if (regionEquals(i, from)) {
copy.write(to, 0, to.length);
i += from.length - 1;
} else {
copy.write(bytes[i]);
}
}
}
set(copy.toByteArray());
}
public boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) {
if (Math.max(offset, otherOffset) + len < 0)
return false;
if (offset + len > length || otherOffset + len > other.length())
return false;
for (int i = 0; i < len; i++) {
if (bytes[offset + i] != other.get(otherOffset + i))
return false;
}
return true;
}
public String toHexString() {
char[] hex = new char[2 * length];
for (int i = 0; i < length; i++) {
hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F);
hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F);
}
return new String(hex);
}
public String toStringUtf8() {
return new String(bytes, 0, length, StandardCharsets.UTF_8);
}
private void setInternal(byte[] bytes) {
this.bytes = bytes.clone();
this.length = bytes.length;
}
private boolean regionEquals(int offset, byte[] other) {
int len = other.length;
if (offset < 0 || offset + len < 0)
return false;
if (offset + len > length)
return false;
for (int i = 0; i < len; i++) {
if (bytes[offset + i] != other[i])
return false;
}
return true;
}
private int check(int index) {
if (index < 0 || index >= length)
throw new IndexOutOfBoundsException(String.valueOf(index));
return index;
}
}

View file

@ -0,0 +1,60 @@
import static org.hamcrest.CoreMatchers.is;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
public class MutableByteStringTest {
@Test
public void testReplaceEmpty() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8));
str.replace(new byte[]{}, new byte[]{'-'});
Assert.assertThat(str.toStringUtf8(), is("-h-e-l-l-o-"));
}
@Test
public void testReplaceMultiple() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8));
str.replace(new byte[]{'l'}, new byte[]{'1', '2', '3'});
Assert.assertThat(str.toStringUtf8(), is("he123123o"));
}
@Test
public void testToHexString() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8));
Assert.assertThat(str.toHexString(), is("68656c6c6f"));
}
@Test
public void testAppend() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8));
str.append((byte) ',');
str.append((byte) ' ');
str.append((byte) 'w');
str.append((byte) 'o');
str.append((byte) 'r');
str.append((byte) 'l');
str.append((byte) 'd');
Assert.assertThat(str.toStringUtf8(), is("hello, world"));
}
@Test
public void testSubstring() {
MutableByteString str = new MutableByteString("hello, world".getBytes(StandardCharsets.UTF_8));
Assert.assertThat(str.substring(0, 5).toStringUtf8(), is("hello"));
Assert.assertThat(str.substring(7, 12).toStringUtf8(), is("world"));
}
@Test
public void testRegionEquals() {
MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8));
Assert.assertThat(str.regionEquals(0, new MutableByteString(new byte[]{'h'}), 0, 1), is(true));
Assert.assertThat(str.regionEquals(0, new MutableByteString(new byte[]{'h'}), 0, 2), is(false));
}
}

View file

@ -0,0 +1,54 @@
//String creation
var str='';
//or
str2=new String();
//String assignment
str="Hello";
//or
str2=', Hey there'; //can use " or '
str=str+str2;//concantenates
//string deletion
delete str2;//this will return true or false, true when it has been successfully deleted, it shouldn't/won't work when the variable has been declared with the keyword 'var', you don't have to initialize variables with the var keyword in JavaScript, but when you do, you cannot 'delete' them. However JavaScript garbage collects, so when the function returns, the variable declared on the function is erased.
//String comparison
str!=="Hello"; //!== not equal-> returns true there's also !===
str=="Hello, Hey there"; //returns true
//compares 'byte' by 'byte'
"Character Z">"Character A"; //returns true, when using > or < operators it converts the string to an array and evalues the first index that is higher than another. (using unicode values) in this case 'Z' char code is 90 (decimal) and 'A' char code is 65, therefore making one string "larger" than the other.
//String cloning and copying
string=str;//Strings are immutable therefore when you assign a string to a variable another one is created. So for two variables to have the 'same' string you have to add that string to an object, and get/set the string from that object
//Check if a string is empty
Boolean(''); //returns false
''[0]; //returns undefined
''.charCodeAt(); //returns NaN
''==0; //returns true
''===0; //returns false
''==false; //returns true
//Append byte to String
str+="\x40";//using + operator before the equal sign on a string makes it equal to str=str+"\x40"
//Extract a substring from a string
//str is "Hello, Hey there@"
str.substr(3); //returns "lo, Hey there@"
str.substr(-5); //returns "here@" negative values just go to the end
str.substr(7,9); //returns "Hey there" index of 7 + 9 characters after the 7
str.substring(3); //same as substr
str.substring(-5); //negative values don't work on substring same as substr(0)
str.substring(7,9); //returns "He" that is, whatever is between index 7 and index 9, same as substring(9,7)
//Replace every occurence of x byte with another string
str3="url,url,url,url,url";
str3.replace(/,/g,'\n') //Regex ,returns the same string with the , replaced by \n
str4=str3.replace(/./g,function(index){//it also supports callback functions, the function will be called when a match has been found..
return index==','?'\n':index;//returns replacement
})
//Join Strings
[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

View file

@ -0,0 +1,10 @@
# If the input is a valid representation of a binary string
# then pass it along:
def check_binary:
. as $a
| reduce .[] as $x
($a;
if $x | (type == "number" and . == floor
and 0 <= . and . <= 255) then $a
else error("\(.) is an invalid representation of a byte")
end );

View file

@ -0,0 +1,70 @@
## Creation of an entity representing an empty binary string
[]
## Assignment
# Unless a check is appropriate, assignment can be done in the
# usual ways, for example:
[0] as $x # assignment to a variable, $x
s as $x # assignment of s to a variable
.key = s # assignment to a key in a JSON object
# If s must be checked, these become:
(s|check_binary) as $x
.key = (s|check_binary)
## Concatenation:
str+str2
## Comparison
[72,101,108,108,111] == ("Hello"|explode) # evaluates to true
# Other jq comparison operators (!=, <, >, <=, >=) can be used as well.
## Cloning and copying
# In jq, all entities are immutable and so the distinction between
# copying and cloning is irrelevant in jq.
# For example, consider the expression "$s[0] = 1"
# in the following:
[0] as $s | $s[0] = 1 | $s
# The result is [0] because the expression "$s[0] = 1"
# evaluates to [1] but does not alter $s. The value of
# $s can be changed by assignment, e.g.
[0] as $s | $s[0] = 1 | . as $s
## Check if an entity represents the empty binary string
length == 0
# or
s == []
## append a byte, b
s + [b] # if the byte, b, is known to be in range
s + ([b]|check_binary) # if b is suspect
## Extract a substring from a string
# jq uses an index origin of 0 for both JSON arrays strings,
# so to extract the substring with indices from m to (n-1)
# inclusive, the expression s[m:n] can be used.
# There are many other possibilities, such as s[m:], s[-1], etc.
## Replace every occurrence of one byte, x, with
## another sequence of bytes presented as an array, a,
## of byte-valued integers:
reduce .[] as $byte ([];
if $byte == x then . + a else . + [$byte] end)

View file

@ -0,0 +1,45 @@
# String assignment. Creation and garbage collection are automatic.
a = "123\x00 abc " # strings can contain bytes that are not printable in the local font
b = "456" * '\x09'
c = "789"
println(a)
println(b)
println(c)
# string comparison
println("(a == b) is $(a == b)")
# String copying.
A = a
B = b
C = c
println(A)
println(B)
println(C)
# check if string is empty
if length(a) == 0
println("string a is empty")
else
println("string a is not empty")
end
# append a byte (actually this is a Char in Julia, and may also be up to 32 bit Unicode) to a string
a= a * '\x64'
println(a)
# extract a substring from string
e = a[1:6]
println(e)
# repeat strings with ^
b4 = b ^ 4
println(b4)
# Replace every occurrence of a string in another string with third string
r = replace(b4, "456" => "xyz")
println(r)
# join strings with *
d = a * b * c
println(d)

View file

@ -0,0 +1,90 @@
class ByteString(private val bytes: ByteArray) : Comparable<ByteString> {
val length get() = bytes.size
fun isEmpty() = bytes.isEmpty()
operator fun plus(other: ByteString): ByteString = ByteString(bytes + other.bytes)
operator fun plus(byte: Byte) = ByteString(bytes + byte)
operator fun get(index: Int): Byte {
require (index in 0 until length)
return bytes[index]
}
fun toByteArray() = bytes
fun copy() = ByteString(bytes.copyOf())
override fun compareTo(other: ByteString) = this.toString().compareTo(other.toString())
override fun equals(other: Any?): Boolean {
if (other == null || other !is ByteString) return false
return compareTo(other) == 0
}
override fun hashCode() = this.toString().hashCode()
fun substring(startIndex: Int) = ByteString(bytes.sliceArray(startIndex until length))
fun substring(startIndex: Int, endIndex: Int) =
ByteString(bytes.sliceArray(startIndex until endIndex))
fun replace(oldByte: Byte, newByte: Byte): ByteString {
val ba = ByteArray(length) { if (bytes[it] == oldByte) newByte else bytes[it] }
return ByteString(ba)
}
fun replace(oldValue: ByteString, newValue: ByteString) =
this.toString().replace(oldValue.toString(), newValue.toString()).toByteString()
override fun toString(): String {
val chars = CharArray(length)
for (i in 0 until length) {
chars[i] = when (bytes[i]) {
in 0..127 -> bytes[i].toChar()
else -> (256 + bytes[i]).toChar()
}
}
return chars.joinToString("")
}
}
fun String.toByteString(): ByteString {
val bytes = ByteArray(this.length)
for (i in 0 until this.length) {
bytes[i] = when (this[i].toInt()) {
in 0..127 -> this[i].toByte()
in 128..255 -> (this[i] - 256).toByte()
else -> '?'.toByte() // say
}
}
return ByteString(bytes)
}
/* property to be used as an abbreviation for String.toByteString() */
val String.bs get() = this.toByteString()
fun main(args: Array<String>) {
val ba = byteArrayOf(65, 66, 67)
val ba2 = byteArrayOf(68, 69, 70)
val bs = ByteString(ba)
val bs2 = ByteString(ba2)
val bs3 = bs + bs2
val bs4 = "GHI£€".toByteString()
println("The length of $bs is ${bs.length}")
println("$bs + $bs2 = $bs3")
println("$bs + D = ${bs + 68}")
println("$bs == ABC is ${bs == bs.copy()}")
println("$bs != ABC is ${bs != bs.copy()}")
println("$bs >= $bs2 is ${bs > bs2}")
println("$bs <= $bs2 is ${bs < bs2}")
println("$bs is ${if (bs.isEmpty()) "empty" else "not empty"}")
println("ABC[1] = ${bs[1].toChar()}")
println("ABC as a byte array is ${bs.toByteArray().contentToString()}")
println("ABCDEF(1..5) = ${bs3.substring(1)}")
println("ABCDEF(2..4) = ${bs3.substring(2,5)}")
println("ABCDEF with C replaced by G is ${bs3.replace(67, 71)}")
println("ABCDEF with CD replaced by GH is ${bs3.replace("CD".bs, "GH".bs)}")
println("GHI£€ as a ByteString is $bs4")
}

View file

@ -0,0 +1,33 @@
'string creation
s$ = "Hello, world!"
'string destruction - not needed because of garbage collection
s$ = ""
'string comparison
s$ = "Hello, world!"
If s$ = "Hello, world!" then print "Equal Strings"
'string copying
a$ = s$
'check If empty
If s$ = "" then print "Empty String"
'append a byte
s$ = s$ + Chr$(33)
'extract a substring
a$ = Mid$(s$, 1, 5)
'replace bytes
a$ = "Hello, world!"
for i = 1 to len(a$)
if mid$(a$,i,1)="l" then
a$=left$(a$,i-1)+"L"+mid$(a$,i+1)
end if
next
print a$
'join strings
s$ = "Good" + "bye" + " for now."

View file

@ -0,0 +1,60 @@
-- String creation and destruction
foo = "Hello world!" -- created by assignment; destruction via garbage collection
-- Strings are binary safe
put numtochar(0) into char 6 of foo
put chartonum(foo.char[6])
-- 0
put str.char[7..foo.length]
-- "world!"
-- String cloning and copying
bar = foo -- copies foo contents to bar
-- String comparison
put (foo=bar) -- TRUE
put (foo<>bar) -- FALSE
-- Check if a string is empty
put (foo=EMPTY)
put (foo="")
put (foo.length=0)
-- Append a byte to a string
put "X" after foo
put chartonum(88) after foo
-- Extract a substring from a string
put foo.char[3..5]
-- Replace every occurrence of a byte (or a string) in a string with another string
----------------------------------------
-- Replace in string
-- @param {string} stringToFind
-- @param {string} stringToInsert
-- @param {string} input
-- @return {string}
----------------------------------------
on replaceAll (stringToFind, stringToInsert, input)
output = ""
findLen = stringToFind.length - 1
repeat while TRUE
currOffset = offset(stringToFind, input)
if currOffset=0 then exit repeat
put input.char[1..currOffset] after output
delete the last char of output
put stringToInsert after output
delete input.char[1..(currOffset + findLen)]
end repeat
put input after output
return output
end
put replaceAll("o", "X", foo)
-- Join strings (4x the same result)
foo = "Hello " & "world!"
foo = "Hello" & numtochar(32) & "world!"
foo = "Hello" & SPACE & "world!"
foo = "Hello" && "world!"

View file

@ -0,0 +1,31 @@
foo = 'foo' -- Ducktyping foo to be string 'foo'
bar = 'bar'
assert (foo == "foo") -- Comparing string var to string literal
assert (foo ~= bar)
str = foo -- Copy foo contents to str
if #str == 0 then -- # operator returns string length
print 'str is empty'
end
str=str..string.char(50)-- Char concatenated with .. operator
substr = str:sub(1,3) -- Extract substring from index 1 to 3, inclusively
str = "string string string string"
-- This function will replace all occurances of 'replaced' in a string with 'replacement'
function replaceAll(str,replaced,replacement)
local function sub (a,b)
if b > a then
return str:sub(a,b)
end
return nil
end
a,b = str:find(replaced)
while a do
str = str:sub(1,a-1) .. replacement .. str:sub(b+1,#str)
a,b = str:find(replaced)
end
return str
end
str = replaceAll (str, 'ing', 'ong')
print (str)
str = foo .. bar -- Strings concatenate with .. operator

View file

@ -0,0 +1,36 @@
a=['123',0,' abc '];
b=['456',9];
c='789';
disp(a);
disp(b);
disp(c);
% string comparison
printf('(a==b) is %i\n',strcmp(a,b));
% string copying
A = a;
B = b;
C = c;
disp(A);
disp(B);
disp(C);
% check if string is empty
if (length(a)==0)
printf('\nstring a is empty\n');
else
printf('\nstring a is not empty\n');
end
% append a byte to a string
a=[a,64];
disp(a);
% substring
e = a(1:6);
disp(e);
% join strings
d=[a,b,c];
disp(d);

View file

@ -0,0 +1,19 @@
(* String creation and destruction *) BinaryString = {}; BinaryString = . ;
(* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65}
-> {12,56,82,65}
-> {83,12,56,65}
(* String comparison *) BinaryString1 === BinaryString2
-> False
(* String cloning and copying *) BinaryString3 = BinaryString1
-> {12,56,82,65}
(* Check if a string is empty *) BinaryString3 === {}
-> False
(* Append a byte to a string *) AppendTo[BinaryString3, 22]
-> {12,56,82,65,22}
(* Extract a substring from a string *) Take[BinaryString3, {2, 5}]
-> {56,82,65,22}
(* Replace every occurrence of a byte (or a string) in a string with another string *)
BinaryString3 /. {22 -> Sequence[33, 44]}
-> {12,56,82,65,33,44}
(* Join strings *) BinaryString4 = Join[BinaryString1 , BinaryString2]
-> {12,56,82,65,83,12,56,65}

View file

@ -0,0 +1,23 @@
var # creation
x = "this is a string"
y = "this is another string"
z = "this is a string"
if x == z: echo "x is z" # comparison
z = "now this is another string too" # assignment
y = z # copying
if x.len == 0: echo "empty" # check if empty
x.add('!') # append a byte
echo x[5..8] # substring
echo x[8 .. ^1] # substring
z = x & y # join strings
import strutils
echo z.replace('t', 'T') # replace occurences of t with T

View file

@ -0,0 +1,2 @@
# String.create 10 ;;
- : string = "\000\023\000\000\001\000\000\000\000\000"

View file

@ -0,0 +1,2 @@
# "Now just remind me" ^ " how the horse moves again?" ;;
- : string = "Now just remind me how the horse moves again?"

View file

@ -0,0 +1,6 @@
# let str = "some text" ;;
val str : string = "some text"
(* modifying a character, OCaml strings are mutable *)
# str.[0] <- 'S' ;;
- : unit = ()

View file

@ -0,0 +1,5 @@
# str = "Some text" ;;
- : bool = true
# "Hello" > "Ciao" ;;
- : bool = true

Some files were not shown because too many files have changed in this diff Show more