Selectively replace multiple instances of a character within a string: Difference between revisions

Added Easylang
(Added Quackery.)
(Added Easylang)
 
(12 intermediate revisions by 11 users not shown)
Line 21:
{{Template:Strings}}
<br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V rep = [‘a’ = [1 = ‘A’, 2 = ‘B’, 4 = ‘C’, 5 = ‘D’], ‘b’ = [1 = ‘E’], ‘r’ = [2 = ‘F’]]
 
F trstring(oldstring, repdict)
DefaultDict[Char, Int] seen
V newchars = ‘’
L(c) oldstring
V i = ++seen[c]
newchars ‘’= I c C repdict & i C repdict[c] {repdict[c][i]} E c
R newchars
 
print(‘abracadabra -> ’trstring(‘abracadabra’, rep))</syntaxhighlight>
 
{{out}}
<pre>
abracadabra -> AErBcadCbFD
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
-- Selectively replace multiple instances of a character within a string
-- J. Carter 2024 Jun
 
with Ada.Strings.Fixed;
with Ada.Text_IO;
 
procedure Selectively_Replace is
procedure Replace
(Letter : in Character; Occurrence : in Positive; Within : in String; By : in Character; Into : in out String)
with Pre => Into'First = Within'First and Into'Last = Within'Last;
-- Finds the index of the Occurrence-th instance of Letter in Within and sets the character in Into at that index to By
-- If there is no such index, has no effect
-- Before the first call to replace, Within should be = Into
 
procedure Replace
(Letter : in Character; Occurrence : in Positive; Within : in String; By : in Character; Into : in out String)
is
Start : Natural := 0;
begin -- Replace
Find : for I in 1 .. Occurrence loop
Start := Ada.Strings.Fixed.Index (Within, Letter & "", Start + 1);
 
if Start = 0 then -- Within has fewer than Occurrence instances of Letter
return;
end if;
end loop Find;
 
Into (Start) := By;
end Replace;
 
Source : constant String := "abracadabra";
 
Result : String := Source;
begin -- Selectively_Replace
Replace (Letter => 'a', Occurrence => 1, Within => Source, By => 'A', Into => Result);
Replace (Letter => 'a', Occurrence => 2, Within => Source, By => 'B', Into => Result);
Replace (Letter => 'a', Occurrence => 4, Within => Source, By => 'C', Into => Result);
Replace (Letter => 'a', Occurrence => 5, Within => Source, By => 'D', Into => Result);
Replace (Letter => 'b', Occurrence => 1, Within => Source, By => 'E', Into => Result);
Replace (Letter => 'r', Occurrence => 2, Within => Source, By => 'F', Into => Result);
Ada.Text_IO.Put_Line (Item => Source & " => " & Result);
end Selectively_Replace;
</syntaxhighlight>
 
{{out}}
<pre>
abracadabra => AErBcadCbFD
</pre>
 
=={{header|ALGOL 68}}==
Line 57 ⟶ 128:
"abracadabra" -> "AErBcadCbFD"
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">replacement: function [rule,ch,order][
loop rule 'r ->
if r\[0] = order -> return r\[1]
return ch
]
multiReplace: function [str, rules][
cntr: #.raw flatten couple keys rules repeat 0 size rules
 
join map str 'ch [
(key? cntr ch)? [
cntr\[ch]: cntr\[ch] + 1
replacement rules\[ch] ch dec cntr\[ch]
] -> ch
]
]
 
print multiReplace "abracadabra" #[
a: [[0 `A`][1 `B`][3 `C`][4 `D`]]
b: [[0 `E`]]
r: [[1 `F`]]
]</syntaxhighlight>
 
{{out}}
 
<pre>AErBcadCbFD</pre>
 
=={{header|AutoHotkey}}==
Line 86 ⟶ 184:
{{out}}
<pre>AErBcadCbFD</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void) {
const char string[] = "abracadabra";
 
char *replaced = malloc(sizeof(string));
strcpy(replaced, string);
 
// Null terminated replacement character arrays
const char *aRep = "ABaCD";
const char *bRep = "E";
const char *rRep = "rF";
 
for (char *c = replaced; *c; ++c) {
switch (*c) {
case 'a':
if (*aRep)
*c = *aRep++;
break;
case 'b':
if (*bRep)
*c = *bRep++;
break;
case 'r':
if (*rRep)
*c = *rRep++;
break;
}
}
 
printf("%s\n", replaced);
 
free(replaced);
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
AErBcadCbFD
</pre>
 
=={{header|C++}}==
Line 112 ⟶ 255:
std::cout << magic << "\n";
}</syntaxhighlight>
{{out}}
<pre>
AErBcadCbFD
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
var TestStr: string = 'abracadabra';
 
 
function FindNthChar(C: char; S: string; N: integer): integer;
{Routine to find the Nth version of C, string S}
begin
for Result:=1 to Length(S) do
if S[Result]=C then
begin
Dec(N);
if N<=0 then exit;
end;
Result:=-1;
end;
 
 
procedure ReplaceNthChar(COld,CNew: char; var S: string; N: integer);
{Find and replace the Nth version COld with CNew}
var Inx: integer;
begin
Inx:=FindNthChar(COld,S,N);
if Inx<1 then exit;
S[Inx]:=CNew;
end;
 
 
procedure SelectivelyReplaceChars(Memo: TMemo);
var I: integer;
begin
Memo.Lines.Add('Before: '+TestStr);
{Do the replacement toward the end of string first}
ReplaceNthChar('a','D',TestStr,5);
ReplaceNthChar('a','C',TestStr,4);
ReplaceNthChar('a','B',TestStr,2);
ReplaceNthChar('r','F',TestStr,2);
ReplaceNthChar('a','A',TestStr,1);
ReplaceNthChar('b','E',TestStr,1);
Memo.Lines.Add('After: '+TestStr);
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
Before: AErBcadCbFD
After: AErBcAdCEFD
Elapsed Time: 1.749 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
<syntaxhighlight>
rs$[] = [ "a" "b" "r" ]
rc[][] = [ [ 1 2 4 5 ] [ 1 ] [ 2 ] ]
rd$[][] = [ [ "A" "B" "C" "D" ] [ "E" ] [ "F" ] ]
s$ = "abracadabra"
#
len cnt[] len rs$[]
for c$ in strchars s$
for i to len rs$[]
if c$ = rs$[i]
cnt[i] += 1
for j to len rc[i][]
if rc[i][j] = cnt[i]
c$ = rd$[i][j]
.
.
.
.
r$ &= c$
.
print r$
</syntaxhighlight>
{{out}}
<pre>
AErBcadCbFD
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun transmogrify = text by text input, Map replacements
Map indexes = text%int[]
text result = ""
for each text ch in input
result.append(when(replacements.has(++indexes[ch] + ch), replacements[indexes[ch] + ch], ch))
end
return result
end
writeLine(transmogrify("abracadabra",
text%text["1a" => "A", "2a" => "B", "4a" => "C", "5a" => "D", "1b" => "E", "2r" => "F"]))
</syntaxhighlight>
{{out}}
<pre>
Line 303 ⟶ 549:
'aABaCD' chg 'bEb' chg 'rrF' chg 'abracadabra'
AErBcadCbFD</syntaxhighlight>
 
 
=={{header|Java}}==
{{trans|JavaScript}}
Here's an example translated from JavaScript.
<syntaxhighlight lang="java">
int findNth(String s, char c, int n) {
if (n == 1) return s.indexOf(c);
return s.indexOf(c, findNth(s, c, n - 1) + 1);
}
 
String selectiveReplace(String s, Set... ops) {
char[] chars = s.toCharArray();
for (Set set : ops)
chars[findNth(s, set.old, set.n)] = set.rep;
return new String(chars);
}
 
record Set(int n, char old, char rep) { }
</syntaxhighlight>
<syntaxhighlight lang="java">
selectiveReplace("abracadabra",
new Set(1, 'a', 'A'),
new Set(2, 'a', 'B'),
new Set(4, 'a', 'C'),
new Set(5, 'a', 'D'),
new Set(1, 'b', 'E'),
new Set(2, 'r', 'F'));
</syntaxhighlight>
{{out}}
<pre>AErBcadCbFD</pre>
 
 
=={{header|JavaScript}}==
Line 573 ⟶ 851:
(AErBcadCbFD)
</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/tables
 
type
# Table of replacements for a character.
Replacements = Table[int, char]
# Table mapping characters to their replacement table.
ReplacementTable = Table[char, Replacements]
 
const ReplTable = {'a': {1: 'A', 2: 'B', 4: 'C', 5: 'D'}.toTable,
'b': {1: 'E'}.toTable,
'r': {2: 'F'}.toTable
}.toTable
 
proc replace(text: string; replTable: ReplacementTable): string =
var counts: Table[char, int] # Follow count of characters.
for c in text:
if c in replTable:
counts.mgetOrPut(c, 0).inc # Update count for this char.
let pos = counts[c]
result.add replTable[c].getOrDefault(pos, c)
else:
result.add c
 
echo replace("abracadabra", ReplTable)
</syntaxhighlight>
 
{{out}}
<pre>AErBcadCbFD
</pre>
 
=={{header|Perl}}==
Line 837 ⟶ 1,146:
caarabadrab -> cABraECdFDb</pre>
 
=={{header|RPL}}==
The character "-" in the rule string means that no replacement should be made for the occurrence concerned. Any other character can be chosen by modifying the code appropriately.
 
Due to the use of <code>INCR</code> and <code>REPL</code> instructions, this program will only work directly on HP48 compatible RPL versions. HP28 users must have programmed their own version of these instructions.
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ 0 → car rule occ
≪ 1 OVER SIZE '''FOR''' j
'''IF''' DUP j DUP SUB car == '''THEN'''
rule 'occ' INCR DUP SUB
'''IF''' DUP "-" == '''THEN''' DROP '''ELSE''' j SWAP REPL '''END'''
'''END NEXT'''
≫ ≫ ''''REPLR'''' STO
|
'''REPLR''' ''( "string" "character" "rule" -- "string" ) ''
loop for j = 1 to string length
if string[j] == character
get todo = rule[++occ]
replace if todo is different from "-"
end if end loop
return string
|}
{{in}}
<pre>
"abracadabra"
≪ "a" "AB-CD" REPLR "b" "E" REPLR "r" "-F" REPLR ≫ EVAL
</pre>
{{out}}
<pre>
1: "AErBcadCbFD"
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">str = "abracadabra"
rules = [
["a", 1, "A"],
["a", 2, "B"],
["a", 4, "C"],
["a", 5, "D"],
["b", 1, "E"],
["r", 2, "F"]]
 
indices = Hash.new{[]}
str.each_char.with_index{|c, i| indices[c] <<= i}
 
rules.each{|char, i, to| str[indices[char][i-1]] = to}
 
p str</syntaxhighlight>
{{out}}
<pre>"AErBcadCbFD"
</pre>
=={{header|sed}}==
<syntaxhighlight lang="sed">s/a\([^a]*\)a\([^a]*a[^a]*\)a\([^a]*\)a/A\1B\2C\3D/
Line 884 ⟶ 1,247:
{{libheader|Wren-regex}}
Not particularly succinct but, thanks to a recently added library method, better than it would have been :)
<syntaxhighlight lang="ecmascriptwren">import "./seq" for Lst
import "./str" for Str
 
Line 903 ⟶ 1,266:
 
Alternatively, using regular expressions (embedded script) producing output as before.
<syntaxhighlight lang="ecmascriptwren">import "./regex" for Regex
 
var s = "abracadabra"
2,083

edits