C #에서 여러 문자열 요소 바꾸기
이 작업을 수행하는 더 좋은 방법이 있습니까?
MyString.Trim().Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower();
하나의 작업으로 유지하기 위해 문자열 클래스를 확장했지만 더 빠른 방법이 있습니까?
public static class StringExtension
{
public static string clean(this string s)
{
return s.Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace(".", "")
.Replace("eacute;", "é").ToLower();
}
}
재미를 위해 (그리고 의견에서 논쟁을 멈추기 위해) 아래의 다양한 예제를 벤치마킹하는 요점을 밀었습니다.
정규식 옵션은 매우 점수가 높습니다. 사전 옵션이 가장 빨리 나타납니다. stringbuilder 교체의 긴 감기 버전은 짧은 손보다 약간 빠릅니다.
더 빨리-아니요. 더 효과적-네, StringBuilder
수업 을 사용한다면 . 구현시 각 작업은 상황에서 성능을 저하시킬 수있는 문자열 사본을 생성합니다. 문자열은 변경 불가능한 객체이므로 각 작업은 수정 된 사본 만 반환합니다.
이 메서드가 Strings
상당한 길이의 배수 에서 활발하게 호출 될 것으로 예상하는 경우 해당 구현을 StringBuilder
클래스 로 "마이그레이션"하는 것이 좋습니다 . 이를 통해 모든 수정이 해당 인스턴스에서 직접 수행되므로 불필요한 복사 작업을 절약 할 수 있습니다.
public static class StringExtention
{
public static string clean(this string s)
{
StringBuilder sb = new StringBuilder (s);
sb.Replace("&", "and");
sb.Replace(",", "");
sb.Replace(" ", " ");
sb.Replace(" ", "-");
sb.Replace("'", "");
sb.Replace(".", "");
sb.Replace("eacute;", "é");
return sb.ToString().ToLower();
}
}
좀 더 읽기 쉬울까요?
public static class StringExtension {
private static Dictionary<string, string> _replacements = new Dictionary<string, string>();
static StringExtension() {
_replacements["&"] = "and";
_replacements[","] = "";
_replacements[" "] = " ";
// etc...
}
public static string clean(this string s) {
foreach (string to_replace in _replacements.Keys) {
s = s.Replace(to_replace, _replacements[to_replace]);
}
return s;
}
}
또한 StringBuilder에 대한 New In Town의 제안을 추가하십시오.
단순히 예쁜 솔루션을 찾고 있고 몇 나노초를 절약 할 필요가 없다면 LINQ 설탕은 어떻습니까?
var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };
var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
더 효율적입니다.
public static class StringExtension
{
public static string clean(this string s)
{
return new StringBuilder(s)
.Replace("&", "and")
.Replace(",", "")
.Replace(" ", " ")
.Replace(" ", "-")
.Replace("'", "")
.Replace(".", "")
.Replace("eacute;", "é")
.ToString()
.ToLower();
}
}
There is one thing that may be optimized in the suggested solutions. Having many calls to Replace()
makes the code to do multiple passes over the same string. With very long strings the solutions may be slow because of CPU cache capacity misses. May be one should consider replacing multiple strings in a single pass.
Another option using linq is
[TestMethod]
public void Test()
{
var input = "it's worth a lot of money, if you can find a buyer.";
var expected = "its worth a lot of money if you can find a buyer";
var removeList = new string[] { ".", ",", "'" };
var result = input;
removeList.ToList().ForEach(o => result = result.Replace(o, string.Empty));
Assert.AreEqual(expected, result);
}
I'm doing something similar, but in my case I'm doing serialization/De-serialization so I need to be able to go both directions. I find using a string[][] works nearly identically to the dictionary, including initialization, but you can go the other direction too, returning the substitutes to their original values, something that the dictionary really isn't set up to do.
Edit: You can use Dictionary<Key,List<Values>>
in order to obtain same result as string[][]
string input = "it's worth a lot of money, if you can find a buyer.";
for (dynamic i = 0, repl = new string[,] { { "'", "''" }, { "money", "$" }, { "find", "locate" } }; i < repl.Length / 2; i++) {
input = input.Replace(repl[i, 0], repl[i, 1]);
}
참고URL : https://stackoverflow.com/questions/1321331/replace-multiple-string-elements-in-c-sharp
'IT TIP' 카테고리의 다른 글
JSON에 대한 JavaScript 연관 배열 (0) | 2020.10.23 |
---|---|
Swift에서 JSON 문자열을 Object로 변환하는 간단하고 깨끗한 방법 (0) | 2020.10.23 |
__eq__는 파이썬에서 어떻게 그리고 어떤 순서로 처리됩니까? (0) | 2020.10.23 |
jQuery를 사용할 때 변수 앞에 "$"를 붙여야하는시기와 이유는 무엇입니까? (0) | 2020.10.23 |
JavaScript 객체를 파괴하는 방법? (0) | 2020.10.23 |