C'è un modo per sostituire tutte le occorrenze di una sottostringa con un'altra stringa in std::string
?
Per esempio:
void SomeFunction(std::string& str)
{
str = str.replace("hello", "world"); //< I'm looking for something nice like this
}
C'è un modo per sostituire tutte le occorrenze di una sottostringa con un'altra stringa in std::string
?
Per esempio:
void SomeFunction(std::string& str)
{
str = str.replace("hello", "world"); //< I'm looking for something nice like this
}
Risposte:
Perché non implementare la tua sostituzione?
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();
}
}
#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");
Ecco la documentazione ufficiale su replace_all.
replace_all
segfault per le versioni boost> 1.43 su Sun Studio per qualsiasi versione <12.3
boost
aumenta notevolmente il tempo di compilazione sui dispositivi embedded. Anche ARMv7 quad core. 100 righe di codice vengono compilate in 2 minuti, senza boost, 2 secondi.
In C ++ 11, puoi farlo come una riga con una chiamata a regex_replace
:
#include <string>
#include <regex>
using std::string;
string do_replace( string const & in, string const & from, string const & to )
{
return std::regex_replace( in, std::regex(from), to );
}
string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;
produzione:
Removeallspaces
from
può essere un'espressione regolare, quindi puoi utilizzare criteri di corrispondenza più sofisticati se necessario. Quello che non vedo è come farlo senza applicare una qualche forma di analisi di espressioni regolari, usando invece solo un'interpretazione diretta dei from
caratteri.
Perché non restituire una stringa modificata?
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
Se hai bisogno di prestazioni, ecco una funzione ottimizzata che modifica la stringa di input, non crea una copia della stringa:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Test:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Produzione:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
Trova e sostituisci sul posto inline basato su modelli:
template<class T>
int inline findAndReplace(T& source, const T& find, const T& replace)
{
int num=0;
typename T::size_t fLen = find.size();
typename T::size_t rLen = replace.size();
for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
{
num++;
source.replace(pos, fLen, replace);
}
return num;
}
Restituisce un conteggio del numero di elementi sostituiti (da utilizzare se si desidera eseguirlo successivamente, ecc.). Per usarlo:
std::string str = "one two three";
int n = findAndReplace(str, "one", "1");
Il modo più semplice (offrendo qualcosa di simile a quello che hai scritto) è usare Boost.Regex , in particolare regex_replace .
std :: string ha i metodi find () e replace () incorporati, ma è più complicato lavorare con loro poiché richiedono la gestione degli indici e delle lunghezze delle stringhe.
Credo che funzionerebbe. Accetta i const char * come parametro.
//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
//ASSERT(find != NULL);
//ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
//search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
//replace the found string with the replacement
source.replace( pos, findLen, replace );
//the next line keeps you from searching your replace string,
//so your could replace "hello" with "hello world"
//and not have it blow chunks.
pos += replaceLen;
}
}
size_type
per una stringa è unsigned
, il >=
controllo nella condizione del ciclo sarà sempre true
. Devi usare std::string::npos
lì.
roll_down_window
// Replace all occurrences of searchStr in str with replacer
// Each match is replaced only once to prevent an infinite loop
// The algorithm iterates once over the input and only concatenates
// to the output, so it should be reasonably efficient
std::string replace(const std::string& str, const std::string& searchStr,
const std::string& replacer)
{
// Prevent an infinite loop if the input is empty
if (searchStr == "") {
return str;
}
std::string result = "";
size_t pos = 0;
size_t pos2 = str.find(searchStr, pos);
while (pos2 != std::string::npos) {
result += str.substr(pos, pos2-pos) + replacer;
pos = pos2 + searchStr.length();
pos2 = str.find(searchStr, pos);
}
result += str.substr(pos, str.length()-pos);
return result;
}
#include <string>
using std::string;
void myReplace(string& str,
const string& oldStr,
const string& newStr) {
if (oldStr.empty()) {
return;
}
for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
Il controllo per oldStr è vuoto è importante. Se per qualsiasi motivo quel parametro è vuoto, rimarrai bloccato in un ciclo infinito.
Ma sì, usa la soluzione collaudata C ++ 11 o Boost se puoi.