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

m
syntax highlighting fixup automation
(Added AutoHotkey)
m (syntax highlighting fixup automation)
Line 23:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">CO in the string "abracadabra", replace the first 'a' with 'A', the second 'a' with 'B'
, the fourth 'a' with 'C', the fifth 'a' with 'D'
the first 'b' with 'E', the second 'r' with 'F'
Line 52:
IF output /= "AErBcadCbFD" THEN print( ( " ** UNEXPECTED RESULT" ) ) FI;
print( ( newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 59:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">str := "abracadabra"
steps := [[1, "a", "A"]
, [2, "a", "B"]
Line 83:
result .= Res[j] = "" ? x[j] : Res[j]
return result
}</langsyntaxhighlight>
{{out}}
<pre>AErBcadCbFD</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <map>
#include <iostream>
#include <string>
Line 111:
 
std::cout << magic << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 119:
=={{header|Factor}}==
{{works with|Factor|0.99 2022-04-03}}
<langsyntaxhighlight lang="factor">USING: assocs formatting grouping kernel random sequences ;
 
CONSTANT: instrs {
Line 141:
 
"abracadabra" test
"abracadabra" randomize test</langsyntaxhighlight>
{{out}}
<pre>
Line 149:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Function replaceChar(Byref S As String) As String
Dim As String A = "ABaCD", B = "Eb", R = "rF"
Dim As Byte pA = 1, pB = 1, pR = 1
Line 173:
S = "caarabadrab"
Print S; " -> "; replaceChar(S)
Sleep</langsyntaxhighlight>
{{out}}
<pre>abracadabra -> AErBcadCbFD
Line 180:
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 205:
s = strings.Replace(s, "F", "r", 1)
fmt.Println(s)
}</langsyntaxhighlight>
 
{{out}}
Line 214:
=={{header|Haskell}}==
As a map-accumulation:
<langsyntaxhighlight lang="haskell">import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
Line 242:
('b', [Just 'E']),
('r', [Nothing, Just 'F'])
]</langsyntaxhighlight>
{{Out}}
<pre>AErBcadCbFD</pre>
Line 248:
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j"> upd=: {{ x (n{I.y=m)} y }}
'ABCD' 'a' upd 0 1 3 4 'E' 'b' upd 0 'F' 'r' upd 1 'abracadabra'
AErBcadCbFD</langsyntaxhighlight>
 
<tt>upd</tt> here takes four arguments -- two on the left (replacement characters, original character) and two on the right(index values for which instances to replace, and the original string).
Line 256:
However, here's a more compact approach (the first item in the left argument is the target, and the rest of the left argument explicitly provides values for every instance of that item in the right argument):
 
<langsyntaxhighlight Jlang="j"> chg=: {{ (}.x) (I.y={.x)} y}}
'aABaCD' chg 'bEb' chg 'rrF' chg 'abracadabra'
AErBcadCbFD</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function findNth(s, c, n) {
if (n === 1) return s.indexOf(c);
return s.indexOf(c, findNth(s, c, n - 1) + 1);
Line 283:
[2, "r", "F"], // the second 'r' with 'F'
])
);</langsyntaxhighlight>
{{out}}
<pre>AErBcadCbFD</pre>
Line 289:
 
Or, expressed as a map-accumulation:
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 352:
// MAIN --
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>AErBcadCbFD</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="ruby">
rep = Dict('a' => Dict(1 => 'A', 2 => 'B', 4 => 'C', 5 => 'D'), 'b' => Dict(1 => 'E'), 'r' => Dict(2 => 'F'))
 
Line 371:
 
println("abracadabra -> ", trstring("abracadabra", rep))
</langsyntaxhighlight>{{out}}Same as Perl.
 
=={{header|Lambdatalk}}==
Line 384:
 
Then we add to the existing set of array functions a new one finding the indexes of some value in a given array.
<syntaxhighlight lang="scheme">
<lang Scheme>
{def A.findindexes
 
Line 404:
-> [0,3,5,7,10]
... and so on
</syntaxhighlight>
</lang>
 
Using findindexes we can translate the aA1 aB2 aC4 aD5 bE1 rF2 sequence into a new one where numbers are replaced by indexes in the given string, here abracadabra.
 
<syntaxhighlight lang="scheme">
<lang Scheme>
{def replacements.rules
{lambda {:w :r}
Line 421:
-> aA0
... and so on
</syntaxhighlight>
</lang>
 
Finally the replacements function will apply this sequence of rules to the word.
 
<syntaxhighlight lang="scheme">
<lang Scheme>
{def replacements
 
Line 450:
-> cABarFECbDd
(cABarFECbDd)
</syntaxhighlight>
</lang>
 
2) second answer using regexps
Line 456:
Here is a quick & dirty answer using the S.replace_once primitive.
 
<syntaxhighlight lang="scheme">
<lang Scheme>
{def multrepl_rex
{lambda {:word :rules}
Line 477:
-> AErBcadCbFD
(AErBcadCbFD)
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 494:
 
my $word = 'abracadabra';
say "$word -> " . transmogrify $word, 'a' => 'AB_CD', 'r' => '_F', 'b' => 'E';</langsyntaxhighlight>
{{out}}
<pre>abracadabra -> AErBcadCbFD</pre>
Line 502:
=={{header|Phix}}==
Couldn't really decide which I prefer so posted both.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">replace_nth</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
Line 526:
<span style="color: #0000FF;">{{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},</span><span style="color: #008000;">'r'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"F"</span><span style="color: #0000FF;">}}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">replace_nths</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abracadabra"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 535:
=={{header|Python}}==
{{trans|Julia}}
<langsyntaxhighlight lang="python">from collections import defaultdict
 
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
Line 548:
 
print('abracadabra ->', trstring('abracadabra', rep))
</syntaxhighlight>
</lang>
 
===Alternative===
<langsyntaxhighlight lang="python">import functools
 
from typing import Iterable
Line 584:
],
)
)</langsyntaxhighlight>
{{out}}
<pre>AErBcadCbFD</pre>
Line 590:
 
Or, as a map-accumulation:
<langsyntaxhighlight lang="python">'''Instance-specific character replacement rules'''
 
from functools import reduce
Line 652:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>AErBcadCbFD</pre>
Line 659:
Set up to not particularly rely on absolute structure of the word. Demonstrate with both the original 'abracadabra' and with a random shuffled instance.
 
<syntaxhighlight lang="raku" perl6line>sub mangle ($str is copy) {
$str.match(:ex, 'a')».from.map: { $str.substr-rw($_, 1) = 'ABaCD'.comb[$++] };
$str.=subst('b', 'E');
Line 668:
say $_, ' -> ', .&mangle given 'abracadabra';
 
say $_, ' -> ', .&mangle given 'abracadabra'.comb.pick(*).join;</langsyntaxhighlight>
 
{{out}}
Line 676:
=={{header|Vlang}}==
A similar approach to the C++ entry.
<langsyntaxhighlight lang="ruby">fn selectively_replace_chars(s string, char_map map[string]string) string {
mut bytes := s.bytes()
mut counts := {
Line 703:
println('$old -> $new')
}
}</langsyntaxhighlight>
 
{{out}}
Line 716:
{{libheader|Wren-regex}}
Not particularly succinct but, thanks to a recently added library method, better than it would have been :)
<langsyntaxhighlight lang="ecmascript">import "./seq" for Lst
import "./str" for Str
 
Line 727:
s = Str.replace(s, "b", "E", 1)
s = Str.replace(s, "r", "F", 2, 1)
System.print(s)</langsyntaxhighlight>
 
{{out}}
Line 735:
 
Alternatively, using regular expressions (embedded script) producing output as before.
<langsyntaxhighlight lang="ecmascript">import "./regex" for Regex
 
var s = "abracadabra"
Line 745:
s = Regex.compile("b").replace(s, "E")
s = Regex.compile("r").replaceAll(s, "F", 2, 1)
System.print(s)</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0;
proc Mangle(S);
char S, A, B, R;
Line 767:
S:= "caarabadrab";
Text(0, S); Text(0, " -> "); Mangle(S); Text(0, S); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
10,327

edits