mirror of
https://github.com/ultimatepp/ultimatepp.git
synced 2026-10-22 13:17:36 -06:00
Core: multi-pattern string Replace
git-svn-id: svn://ultimatepp.org/upp/trunk@7716 f0d560ea-af0d-0410-9eb7-867de7ffcac7
This commit is contained in:
parent
9bdbf8ad25
commit
c7a418ccb4
8 changed files with 111 additions and 28 deletions
|
|
@ -905,4 +905,56 @@ void NanoStrings::DumpProfile()
|
|||
}
|
||||
}
|
||||
|
||||
template <class CHR, class T>
|
||||
T Replace__(const T& s, const Vector<T>& find, const Vector<T>& replace)
|
||||
{
|
||||
ASSERT(find.GetCount() == replace.GetCount());
|
||||
|
||||
T r;
|
||||
int i = 0;
|
||||
while(i < s.GetCount()) {
|
||||
int best = -1;
|
||||
int bestlen = 0;
|
||||
int len = s.GetCount() - i;
|
||||
const CHR *q = ~s + i;
|
||||
for(int j = 0; j < replace.GetCount(); j++) {
|
||||
const T& m = find[j];
|
||||
int l = m.GetCount();
|
||||
if(l <= len && l > bestlen && memcmp(~m, q, l * sizeof(CHR)) == 0) {
|
||||
bestlen = l;
|
||||
best = j;
|
||||
}
|
||||
}
|
||||
if(best >= 0) {
|
||||
i += bestlen;
|
||||
r.Cat(replace[best]);
|
||||
}
|
||||
else {
|
||||
r.Cat(*q);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
String Replace(const String& s, const Vector<String>& find, const Vector<String>& replace)
|
||||
{
|
||||
return Replace__<char>(s, find, replace);
|
||||
}
|
||||
|
||||
String Replace(const String& s, const VectorMap<String, String>& fr)
|
||||
{
|
||||
return Replace__<char>(s, fr.GetKeys(), fr.GetValues());
|
||||
}
|
||||
|
||||
WString Replace(const WString& s, const Vector<WString>& find, const Vector<WString>& replace)
|
||||
{
|
||||
return Replace__<wchar>(s, find, replace);
|
||||
}
|
||||
|
||||
WString Replace(const WString& s, const VectorMap<WString, WString>& fr)
|
||||
{
|
||||
return Replace__<wchar>(s, fr.GetKeys(), fr.GetValues());
|
||||
}
|
||||
|
||||
END_UPP_NAMESPACE
|
||||
|
|
|
|||
Loading…
Reference in a new issue