replace strings inside a substring
I have this string: "The quick brown f0x jumps 0ver the lazy d0g, the quick brown f0x jumps 0ver the lazy d0g.".
I need a function that will replace all zeros between "brown" and "lazy" with "o". So the output will look like this: "The quick brown fox jumps over the lazy d0g, the quick brown fox jumps over the开发者_StackOverflow中文版 lazy d0g.". So it will look all over the string and most importantly will leave all other zeros intact.
function(text, leftBorder, rightBorder, searchString, replaceString) : string;
Is there any good algorithm?
If you have Python, here's an example using just string manipulation, eg split()
, indexing
etc. Your programming language should have these features as well.
>>> s="The quick brown f0x jumps 0ver the lazy d0g, the quick brown f0x jumps 0ver the lazy d0g."
>>> words = s.split("lazy")
>>> for n,word in enumerate(words):
... if "brown" in word:
... w = word.split("brown")
... w[-1]=w[-1].replace("0","o")
... word = 'brown'.join(w)
... words[n]=word
...
>>> 'lazy'.join(words)
'The quick brown fox jumps over the lazy d0g, the quick brown fox jumps over the lazy d0g.'
>>>
The steps:
- Split the words on "lazy" to an array A
- Go through each element in A to look for "brown"
- if found , split on "brown" into array B. The part you are going to change is the last element
- replace it with whatever methods your programming language provides
- join back the array B using "brown"
- update this element in the first array A
- lastly, join the whole string back using "lazy"
精彩评论