여러 String.Replaces의 대안
이 질문에 이미 답변이 있습니다.
- C # 8 답변 에서 여러 문자열 요소 바꾸기
내 코드는 String.Replace
연속으로 여러 번 사용됩니다 .
mystring = mystring.Replace("somestring", variable1);
mystring = mystring.Replace("somestring2", variable2);
mystring = mystring.Replace("somestring3", variable1);
나는 그것을하는 더 좋고 더 빠른 방법이 있다고 생각한다. 무엇을 제안 하시겠습니까?
'쉬운'대안은 StringBuilder를 사용하십시오 ....
StringBuilder sb = new StringBuilder("11223344");
string myString =
sb
.Replace("1", string.Empty)
.Replace("2", string.Empty)
.Replace("3", string.Empty)
.ToString();
무슨 일이 일어나고 있는지 이해 하기 어렵게 만드는 방법을 찾고 있습니까?
그렇다면 정규식이 당신의 친구라면
var replacements = new Dictionary<string,string>()
{
{"somestring",someVariable1},
{"anotherstring",someVariable2}
};
var regex = new Regex(String.Join("|",replacements.Keys.Select(k => Regex.Escape(k))));
var replaced = regex.Replace(input,m => replacements[m.Value]);
라이브 : http://rextester.com/SXXB8348
최소한 다음과 같이 문장을 연결할 수 있습니다.
mystring = mystring.Replace("somestring", variable1)
.Replace("somestring2", variable2)
.Replace("somestring3", variable3);
Replace
세 번 전화 하는 것은 유효한 대답 일뿐만 아니라 선호하는 대답 일 수 있습니다.
RegEx는 Parse, Execute, Formulate의 세 단계를 거칩니다 . 그러나 String.Replace
하드 코딩되어 있으므로 많은 경우 속도가 뛰어납니다. 복잡한 RegEx는 올바른 형식의 Replace
문 체인만큼 가독성이 떨어 집니다. ( Jonathan 의 솔루션과 Daniel 의 솔루션 비교 )
그것이 당신 Replace
의 경우에 더 낫다고 확신하지 못한다면 , 그것으로 경쟁하십시오! 두 방법을 나란히 시도하고 a Stopwatch
를 사용하여 데이터를 사용할 때 절약되는 밀리 초를 확인하십시오.
그러나 필요한 경우가 아니면 코드를 최적화 하지 마십시오 ! 모든 개발자는 3 밀리 초 더 빠른 성능을 제공하는 스파게티 더미보다 가독성과 유지 보수성을 선호합니다.
이 문서 Regex : 단일 패스에서 여러 문자열을 C # 으로 바꾸면 도움이 될 수 있습니다.
static string MultipleReplace(string text, Dictionary replacements) {
return Regex.Replace(text,
"(" + String.Join("|", adict.Keys.ToArray()) + ")",
delegate(Match m) { return replacements[m.Value]; }
);
}
// somewhere else in code
string temp = "Jonathan Smith is a developer";
adict.Add("Jonathan", "David");
adict.Add("Smith", "Seruyange");
string rep = MultipleReplace(temp, adict);
데이터 구성 방식 (대체 대상) 또는 보유한 데이터 수에 따라 다릅니다. 배열과 루프가 좋은 방법 일 수 있습니다.
string[] replaceThese = {"1", "2", "3"};
string data = "replace1allthe2numbers3";
foreach (string curr in replaceThese)
{
data = data.Replace(curr, string.Empty);
}
RegEx를 사용하지 않으려면이 클래스를 프로젝트에 추가하면
'MultipleReplace'확장 메서드를 사용합니다.
public static class StringExtender
{
public static string MultipleReplace(this string text, Dictionary<string, string> replacements)
{
string retVal = text;
foreach (string textToReplace in replacements.Keys)
{
retVal = retVal.Replace(textToReplace, replacements[textToReplace]);
}
return retVal;
}
}
그런 다음이 코드를 사용할 수 있습니다.
string mystring = "foobar";
Dictionary<string, string> stringsToReplace = new Dictionary<string,string>();
stringsToReplace.Add("somestring", variable1);
stringsToReplace.Add("somestring2", variable2);
stringsToReplace.Add("somestring3", variable1);
mystring = mystring.MultipleReplace(stringsToReplace);
내가 선호하는 방법은의 기능을 사용하여 Regex
다중 교체 문제를 해결하는 것입니다. 이 접근 방식의 유일한 문제는 string
대체 할 하나만 선택하면된다는 것 입니다.
다음은 all '/'
또는 ':'
로 대체 '-'
하여 유효한 파일 이름을 만듭니다.
Regex.Replace("invalid:file/name.txt", @"[/:]", "-");
참고 URL : https://stackoverflow.com/questions/12007358/alternative-to-multiple-string-replaces
'development' 카테고리의 다른 글
PHP : 배열 키 대소 문자를 구분하지 않음 * 조회? (0) | 2020.12.03 |
---|---|
Parcelable 인터페이스를 사용할 때 null 값을 직렬화하는 방법 (0) | 2020.12.03 |
자리 표시 자 텍스트 변경 (0) | 2020.12.03 |
Entity Framework 및 호출 context.dispose () (0) | 2020.12.03 |
gulp에서 파일을 복사 할 때 폴더 구조를 제거 할 수 있습니까? (0) | 2020.12.03 |