How to find and replace string?
Replace first match
Use a combination of std::string::find
and std::string::replace
.
Find the first match:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
Replace the first match:
s.replace(pos, toReplace.length(), "new text");
A simple function for your convenience:
void replace_first(
std::string& s,
std::string const& toReplace,
std::string const& replaceWith
) {
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return;
s.replace(pos, toReplace.length(), replaceWith);
}
Usage:
replace_first(s, "text to replace", "new text");
Demo.
Replace all matches
Define this O(n) method using std::string
as a buffer:
void replace_all(
std::string& s,
std::string const& toReplace,
std::string const& replaceWith
) {
std::string buf;
std::size_t pos = 0;
std::size_t prevPos;
// Reserves rough estimate of final size of string.
buf.reserve(s.size());
while (true) {
prevPos = pos;
pos = s.find(toReplace, pos);
if (pos == std::string::npos)
break;
buf.append(s, prevPos, pos - prevPos);
buf += replaceWith;
pos += toReplace.size();
}
buf.append(s, prevPos, s.size() - prevPos);
s.swap(buf);
}
Usage:
replace_all(s, "text to replace", "new text");
Demo.
Boost
Alternatively, use boost::algorithm::replace_all
:
#include <boost/algorithm/string.hpp>
using boost::replace_all;
Usage:
replace_all(s, "text to replace", "new text");
How do I Search/Find and Replace in a standard string?
Why not implement your own replace?
void myReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr)
{
std::string::size_type pos = 0u;
while((pos = str.find(oldStr, pos)) != std::string::npos){
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
String find and replace
I'm not sure what are you wanna do but if i've got it you can do this :
private string ReplaceFirstOccurrence(string Source, string Find, string Replace)
{
int Place = Source.IndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
var result =ReplaceFirstOccurrence(text,"~"+input,"");
Find and replace string within string
You can use regex:
example1 = Regex.Replace(example1, "\(.*\)", "(whatever i put here)")
If you just want to know if there are opening anc closing brackets you can either use regex:
Dim containsBrackets = Regex.IsMatch(example1, "\(.*\)")
or the VB.NET Like
operator:
Dim containsBrackets = example1 like "*(*)*"
or String.IndexOf
:
Dim indexOfOpeningBracket = example1.IndexOf("(")
Dim indexOfClosingBracket = example1.IndexOf(")", indexOfOpeningBracket + 1)
Dim containsBrackets = indexOfOpeningBracket >= 0 AndAlso indexOfClosingBracket > 0
This also enables you to get the part between the parentheses with Substring
:
If containsBrackets
indexOfOpeningBracket += 1 ' you dont want the parentheses itself but just the content
Dim partBetween = example1.Substring(indexOfOpeningBracket, indexOfClosingBracket - indexOfOpeningBracket)
End If
find and replace string
<script type="text/javascript">
function replaceScript() {
var toReplace = 'http://google.com';
var replaceWith ='http://yahoo.com';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>
Then initialise in the body tag to do on page load.
<body onload="replaceScript();">
Should work fine and replace all instances in html body code.
If it is in an iframe with id "external_iframe" then you would modify document.body.innerHTML to be:
window.frames['external_iframe'].document.body.innerHTML
Although I'm not convinced you can use it for an external site.
Seems to be some info here: Javascript Iframe innerHTML
Replace words in a string - Ruby
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
Find and replace string values in list
words = [w.replace('[br]', '<br />') for w in words]
These are called List Comprehensions.
Find and replace strings in vim on multiple lines
The :&&
command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):
:6,10s/<search_string>/<replace_string>/g | 14,18&&
If you have many ranges though, I'd rather use a loop:
:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor
Related Topics
How to Compile Qt 5 Under Windows or Linux, 32 or 64 Bit, Static or Dynamic on Visual Studio or G++
C++ Convert from 1 Char to String
Singleton Instance Declared as Static Variable of Getinstance Method, Is It Thread-Safe
Purpose of Trigraph Sequences in C++
Convert Mat to Array/Vector in Opencv
Why Use Functors Over Functions
How to Read a Binary File into a Vector of Unsigned Chars
Concatenate Two String Literals
Redirect Stdout/Stderr to a String
How Do Sizeof(Arr)/Sizeof(Arr[0]) Work
How to Use C++ Classes with Ctypes
How to Simulate "Press Any Key to Continue"
Difference Between Char* and Char[]
How to Get a "Useful" C++ Binary Search Algorithm
What Is Shared_Ptr's Aliasing Constructor For
Borderless Window Using Areo Snap, Shadow, Minimize Animation, and Shake