나는 문자열을 말한다
"Hello! world!"
트림을 제거하거나 제거하고 싶습니다! 세상에서 벗어 났지만 안돼
나는 문자열을 말한다
"Hello! world!"
트림을 제거하거나 제거하고 싶습니다! 세상에서 벗어 났지만 안돼
답변:
"Hello! world!".TrimEnd('!');
편집하다:
이 유형의 질문에서 내가 주목 한 것은 주어진 문자열의 마지막 문자를 제거하는 것이 좋습니다. 그러나 이것은 트림 방법의 정의를 충족시키지 못합니다.
트림-이 인스턴스의 시작과 끝에서 모든 공백 문자를 제거합니다.
이 정의에서 문자열에서 마지막 문자 만 제거하는 것은 나쁜 해결책입니다.
"문자열에서 마지막 문자 다듬기"를 원하면 다음과 같이해야합니다.
확장 방법의 예 :
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
참고 동일한 값, 즉 모든 문자를 제거 (!!)를 제거의 모든 실존 위의 방법을 원하는 경우 '!' 문자열의 끝에서 마지막 문자 만 제거하려면 다음을 사용해야합니다.
else { return str.Remove(str.Length - 1); }
String withoutLast = yourString.Substring(0,(yourString.Length - 1));
if (yourString.Length > 1)
withoutLast = yourString.Substring(0, yourString.Length - 1);
또는
if (yourString.Length > 1)
withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);
... 공백이 아닌 문자를 끝에서 제거하려는 경우.
TrimEnd()메소드 가 없기 때문일 수 있으며 , 존재하는 경우 Substring(..)짧은 문자열 에서 후속 호출이 실패 할 수 있습니다.
string s1 = "Hello! world!";
string s2 = s1.Trim('!');
이것을 사용할 수도 있습니다 :
public static class Extensions
{
public static string RemovePrefix(this string o, string prefix)
{
if (prefix == null) return o;
return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
}
public static string RemoveSuffix(this string o, string suffix)
{
if(suffix == null) return o;
return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
}
}
@Damian Leszczyński-Vash의 약간 수정 된 버전으로 특정 문자 만 제거됩니다.
public static class StringExtensions
{
public static string TrimLastCharacter(this string str, char character)
{
if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
{
return str;
}
return str.Substring(0, str.Length - 1);
}
}
TrimEnd를 사용하여 이미 인라인을 사용하고 있고 기뻐했기 때문에 확장 기능을 작성하는 길을갔습니다.
static class Extensions
{
public static string RemoveLastChars(this String text, string suffix)
{
char[] trailingChars = suffix.ToCharArray();
if (suffix == null) return text;
return text.TrimEnd(trailingChars);
}
}
정적 클래스; P를 사용하여 클래스에 네임 스페이스를 포함시켜야하며 사용법은 다음과 같습니다.
string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");
이를 단순화하는 확장 클래스 예제 :-
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
용법
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
'!'를 제거하려면 특정 표현의 문자 (귀하의 경우 "world")를 사용하면이 정규 표현식을 사용할 수 있습니다
string input = "Hello! world!";
string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);
// result: "Hello! world"
$ 1 특수 문자에는 일치하는 "world"표현식이 모두 포함되며 원래 "world!"를 대체하는 데 사용됩니다. 표현