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

m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(3 intermediate revisions by 3 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|ALGOL 68}}==
Line 450 ⟶ 470:
'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 1,050 ⟶ 1,102:
</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 1,097 ⟶ 1,168:
{{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 1,116 ⟶ 1,187:
 
Alternatively, using regular expressions (embedded script) producing output as before.
<syntaxhighlight lang="ecmascriptwren">import "./regex" for Regex
 
var s = "abracadabra"
9,476

edits