문자열 매개 변수가있는 C # TrimStart
나는에 대한 문자열 확장 방법을 찾고 있어요 TrimStart()
그리고 TrimEnd()
그 문자열 매개 변수를 받아들입니다.
직접 만들 수는 있지만 항상 다른 사람들이하는 일을 보는 데 관심이 있습니다.
어떻게 할 수 있습니까?
(정확히 일치하는) 문자열의 모든 발생을 트리밍하려면 다음과 같이 사용할 수 있습니다.
TrimStart
public static string TrimStart(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.StartsWith(trimString))
{
result = result.Substring(trimString.Length);
}
return result;
}
TrimEnd
public static string TrimEnd(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.EndsWith(trimString))
{
result = result.Substring(0, result.Length - trimString.Length);
}
return result;
}
대상의 시작 / 끝에서 trimChars의 문자를 트리밍하려면 (예 : "foobar'@"@';".TrimEnd(";@'")
반환 "foobar"
) 다음을 사용할 수 있습니다.
TrimStart
public static string TrimStart(this string target, string trimChars)
{
return target.TrimStart(trimChars.ToCharArray());
}
TrimEnd
public static string TrimEnd(this string target, string trimChars)
{
return target.TrimEnd(trimChars.ToCharArray());
}
TrimStart 및 TrimEnd는 문자 배열을받습니다. 이것은 다음과 같이 문자열을 char 배열로 전달할 수 있음을 의미합니다.
var trimChars = " .+-";
var trimmed = myString.TrimStart(trimChars.ToCharArray());
따라서 문자열 매개 변수를 사용하는 오버로드가 필요하지 않습니다.
나는 질문이 더 큰 문자열의 시작 부분에서 특정 문자열을 자르려는 것이라고 생각했습니다.
예를 들어 "hellohellogoodbyehello"라는 문자열이있는 경우 TrimStart ( "hello")를 호출하려고하면 "goodbyehello"가 반환됩니다.
이 경우 다음과 같은 코드를 사용할 수 있습니다.
string TrimStart(string source, string toTrim)
{
string s = source;
while (s.StartsWith(toTrim))
{
s = s.Substring(toTrim.Length - 1);
}
return s;
}
문자열 트리밍을 많이해야하는 경우에는 매우 효율적이지 않지만 몇 가지 경우에만 간단하고 작업을 완료 할 수 있습니다.
전체 문자열을 일치시키고 여러 하위 문자열을 할당하지 않으려면 다음을 사용해야합니다.
public static string TrimStart(this string source, string value, StringComparison comparisonType)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
int valueLength = value.Length;
int startIndex = 0;
while (source.IndexOf(value, startIndex, comparisonType) == startIndex)
{
startIndex += valueLength;
}
return source.Substring(startIndex);
}
public static string TrimEnd(this string source, string value, StringComparison comparisonType)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
int sourceLength = source.Length;
int valueLength = value.Length;
int count = sourceLength;
while (source.LastIndexOf(value, count, comparisonType) == count - valueLength)
{
count -= valueLength;
}
return source.Substring(0, count);
}
에서 dotnetperls.com ,
공연
불행히도 TrimStart 방법은 크게 최적화되지 않았습니다. 특정 상황에서는이를 능가 할 수있는 문자 기반 반복 코드를 작성할 수 있습니다. TrimStart를 사용하려면 배열을 만들어야하기 때문입니다.
그러나 사용자 지정 코드에 반드시 배열이 필요한 것은 아닙니다. 그러나 빠르게 개발 된 응용 프로그램의 경우 TrimStart 방법이 유용합니다.
C #에는 기본 제공 함수가 없지만 예상 한대로 정확하게 작동하는 자체 확장을 작성할 수 있습니다.
함께합니다 같이 IndexOf / lastIndexOf에서도 민감한 여부 대소 문자 구분 / 문화 인 경우, 당신이 선택할 수 있습니다.
"반복 트림"기능도 구현했습니다.
하나 개의 기능이 TrimStr(..)
모두 트림 처리, 플러스 구현하는 세 가지 기능 .TrimStart(...)
, .TrimEnd(...)
그리고 .Trim(..)
닷넷 트림과의 호환성을 위해이 :
public static class Extension
{
public static string TrimStr(this string str, string trimStr,
bool trimEnd = true, bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
int strLen;
do
{
if (!(str ?? "").EndsWith(trimStr)) return str;
strLen = str.Length;
{
if (trimEnd)
{
var pos = str.LastIndexOf(trimStr, comparisonType);
if ((!(pos >= 0)) || (!(str.Length - trimStr.Length == pos))) break;
str = str.Substring(0, pos);
}
else
{
var pos = str.IndexOf(trimStr, comparisonType);
if (!(pos == 0)) break;
str = str.Substring(trimStr.Length, str.Length - trimStr.Length);
}
}
} while (repeatTrim && strLen > str.Length);
return str;
}
// the following is C#6 syntax, if you're not using C#6 yet
// replace "=> ..." by { return ... }
public static string TrimEnd(this string str, string trimStr,
bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> TrimStr(str, trimStr, true, repeatTrim, comparisonType);
public static string TrimStart(this string str, string trimStr,
bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> TrimStr(str, trimStr, false, repeatTrim, comparisonType);
public static string Trim(this string str, string trimStr, bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> str.TrimStart(trimStr, repeatTrim, comparisonType)
.TrimEnd(trimStr, repeatTrim, comparisonType);
}
이제 다음과 같이 사용할 수 있습니다.
Console.WriteLine("Sammy".TrimEnd("my"));
Console.WriteLine("moinmoin gibts gips? gips gibts moin".TrimStart("moin", false));
Console.WriteLine("moinmoin gibts gips? gips gibts moin".Trim("moin").Trim());
출력을 생성하는
샘
모인 깁스? 깁스 깁스 모인 깁스
깁스? 깁스 깁스
I'm assuming you mean that, for example, given the string "HelloWorld" and calling the function to 'trim' the start with "Hello" you'd be left with "World". I'd argue that this is really a substring operation as you're removing a portion of the string of known length, rather than a trim operation which removes an unknown length of string.
As such, we created a couple of extension methods named SubstringAfter
and SubstringBefore
. It would be nice to have them in the framework, but they aren't so you need to implement them yourselves. Don't forget to have a StringComparison
parameter, and to use Ordinal
as the default if you make it optional.
If you did want one that didn't use the built in trim functions for whatever reasons, assuming you want an input string to use for trimming such as " ~!" to essentially be the same as the built in TrimStart with [' ', '~', '!']
public static String TrimStart(this string inp, string chars)
{
while(chars.Contains(inp[0]))
{
inp = inp.Substring(1);
}
return inp;
}
public static String TrimEnd(this string inp, string chars)
{
while (chars.Contains(inp[inp.Length-1]))
{
inp = inp.Substring(0, inp.Length-1);
}
return inp;
}
Function to trim start/end of a string with a string parameter, but only once (no looping, this single case is more popular, loop can be added with an extra param to trigger it) :
public static class BasicStringExtensions
{
public static string TrimStartString(this string str, string trimValue)
{
if (str.StartsWith(trimValue))
return str.TrimStart(trimValue.ToCharArray());
//otherwise don't modify
return str;
}
public static string TrimEndString(this string str, string trimValue)
{
if (str.EndsWith(trimValue))
return str.TrimEnd(trimValue.ToCharArray());
//otherwise don't modify
return str;
}
}
As mentioned before, if you want to implement the "while loop" approach, be sure to check for empty string otherwise it can loop forever.
참고URL : https://stackoverflow.com/questions/4335878/c-sharp-trimstart-with-string-parameter
'IT TIP' 카테고리의 다른 글
if 문 다음에 나오는 변수 선언 (0) | 2020.12.07 |
---|---|
페이지의 특정 부분 만 표시하는 iframe (0) | 2020.12.07 |
const 비 정수 지수로 pow () 최적화? (0) | 2020.12.07 |
페이지로드시 CSS 전환 실행 중지 (0) | 2020.12.07 |
Android에서 머티리얼 디자인 원형 진행률 표시 줄을 구현하는 방법 (0) | 2020.12.07 |