How to replace limited number of occurrences in string
You can get the first 3 ranges occurrences of that string and then you can iterate the ranges in reverse order replacing the subranges:
var string = "blabla[R]bla[R]blaaa[R]blabla[R]bla[R]bla"
var ranges: [Range<String.Index>] = []
var start = string.startIndex
while start < string.endIndex,
let range = string.range(of: "[R]", range: start..<string.endIndex) {
ranges.append(range)
start = range.upperBound
if ranges.count == 3 { break }
}
for range in ranges.reversed() {
string.replaceSubrange(range, with: "(X)")
}
print(string) // blabla(X)bla(X)blaaa(X)blabla[R]bla[R]bla
Python: how to replace a substring with a number of its occurences?
Take advantage of the standard library:
from itertools import groupby
st = "abbbccccaaaAAbccc"
print("".join("{}{}".format(key, len(list(group))) for key, group in groupby(st)))
Output:
a1b3c4a3A2b1c3
>>>
How to replace a specified number of occurrences of a cstring in C?
Updating previous replace solution
Don't look for all occurence, stop if you reach the limit with something like:
if (count >= max)
break;
// You must free the result if result is non-NULL.
char *str_replace(const char *orig, char *rep, char *with, int max) {
char *result; // the return string
const char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
// sanity checks and initialization
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL; // empty rep causes infinite loop during count
if (!with)
with = "";
len_with = strlen(with);
// count the number of replacements needed
ins = orig;
for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
if (count >= max)
break;
}
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
int main(void)
{
const char* input = "foo bar one bar two bar three bar";
char *replace = str_replace(input, "bar", "john", 2);
printf("before: %s\nafter: %s\n", input, replace);
free(replace);
return 0;
}
will output
before: foo bar one bar two bar three bar
after: foo john one john two bar three bar
replacing only the first occurance of a character in string
The replace function by default is replacing all the occurrences of 1
in the string. You can limit this using the correct syntax as below
Syntax
string.replace(oldvalue, newvalue, count)
If you want only the first occurrence to get replaced you should use
s=s.replace(s[0],'9',1)
How do I replace all occurrences of a string in JavaScript?
In the latest versions of most popular browsers, you can use replaceAll
as shown here:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.
For Node.js and compatibility with older/non-current browsers:
Note: Don't use the following solution in performance critical code.
As an alternative to regular expressions for a simple literal string, you could use
str = "Test abc test test abc test...".split("abc").join("");
The general pattern is
str.split(search).join(replacement)
This used to be faster in some cases than using replaceAll
and a regular expression, but that doesn't seem to be the case anymore in modern browsers.
Benchmark: https://jsben.ch/TZYzj
Conclusion:
If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.
How do I replace a specific occurrence of a string in a string?
This will only replace the second instance of title1
(and any subsequent instances) after the first:
string output = Regex.Replace(input, @"(?<=title1.*)title1", "title2");
However, if there are more than 2 instances, it may not be what you want. It's a little crude, but you can do this to handle any number of occurrences:
int i = 1;
string output = Regex.Replace(input, @"title1", m => "title" + i++);
Sed to replace certain number of occurrences
The best I can offer is
sed -r '2,$ { s/(^|,) *[a-z]/\U&/; s//\U&/; }'
The \U&
trick uses the fact that the upper case version of a space is still a space; this is to make the repetition shorter. Because captures are no longer used, the regex can be simplified a little.
In the second s
command, the //
is a stand-in for the most recently attempted regex, so the first one is essentially executed a second time (this time matching what was originally the second appearance).
Since /1
doesn't actually do anything (replacing the first occurrence is default), I took the liberty of removing it.
Count the number of occurrences of a character in a string
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring
sub
in the range[start, end]
. Optional argumentsstart
andend
are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
Fastest method to replace all instances of a character in a string
The easiest would be to use a regular expression with g
flag to replace all instances:
str.replace(/foo/g, "bar")
This will replace all occurrences of foo
with bar
in the string str
. If you just have a string, you can convert it to a RegExp object like this:
var pattern = "foobar",
re = new RegExp(pattern, "g");
Related Topics
Firebase Auth Internal Error on Login Attempt
How to Draw Line Node Keep Same Size in Camera as Measure App in Iphone
Is Dispatchsemaphore a Good Replacement for Nslock
Swift Combine Publishers VS Completion Handler and When to Cancel
Symbol Is Considered to Be an Identifier, Not an Operator
Swift Codable - Parse JSON Array Which Can Contain Different Data Type
Is a Static Boolean a Reference Type in Swift
Metal Ray Tracing - Scenekit or Realitykit
Reflection with Swift - Get Functions Name of a Class
How to Rotate an Arkit 4X4 Matrix Around Y Using Apple's Simd Library
How Does Let X Where X.Hassuffix("Pepper") Work
How to Retrieve a Value from Dictionary in Swift 3
How to Record My MAC's Internal Sound, Not the Microphone!, Using Avcapturesession
Swift 3/Macos: Open Window on Certain Screen
"Use Default Container" Doesn't Show in Icloud Capabilities
How to Cast a Metaclass Object to a Protocol Type in Swift
Nsurlsessiondatadelegate Method Didreceivedata and Others Are Not Called