dlang语言以下代码用原生方式改为更高效率的算法private alias toLowerAll = stdstringtoLower;ref string replaceStringTauto ref T allStr auto ref T searchStr auto ref T replaceStr bool isCaseSensitive = trueif isSomeString!T
- 使用标准库的replace函数替代手动替换字符串的方式:
ref string replaceString(T)(auto ref T allStr, auto ref T searchStr, auto ref T replaceStr, bool isCaseSensitive = true) if (isSomeString!T) { if(isCaseSensitive){ allStr = std.algorithm.replace(allStr, searchStr, replaceStr); }else{ auto lowerAllStr = allStr.toLowerAll(); auto lowerSearchStr = searchStr.toLowerAll(); allStr = std.algorithm.replace(lowerAllStr, lowerSearchStr, replaceStr).idup; } return allStr; }
- 使用std.regex进行正则表达式匹配和替换:
import std.regex;
ref string replaceString(T)(auto ref T allStr, auto ref T searchStr, auto ref T replaceStr, bool isCaseSensitive = true) if (isSomeString!T) { auto regexStr = isCaseSensitive ? searchStr : searchStr.toLowerAll(); auto regex = regex(regexStr, isCaseSensitive ? "" : "i"); allStr = regex.replace(allStr, replaceStr).idup; return allStr; }
- 使用std.algorithm.split和std.algorithm.join进行字符串分割和拼接:
ref string replaceString(T)(auto ref T allStr, auto ref T searchStr, auto ref T replaceStr, bool isCaseSensitive = true) if (isSomeString!T) { auto lowerAllStr = isCaseSensitive ? allStr : allStr.toLowerAll(); auto lowerSearchStr = searchStr.toLowerAll(); auto parts = std.algorithm.split(lowerAllStr, lowerSearchStr); allStr = std.algorithm.join(parts, replaceStr).idup; return allStr;
原文地址: https://www.cveoy.top/t/topic/ftge 著作权归作者所有。请勿转载和采集!