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