문자열에서 마지막 문자 다듬기


157

나는 문자열을 말한다

"Hello! world!" 

트림을 제거하거나 제거하고 싶습니다! 세상에서 벗어 났지만 안돼


1
어쩌면 그것은 귀하의 요청을 넘어서는 것이지만 제안한 정규식 사용에 대해 잠시 생각해 보라고 요청할 수 있습니까?
Marcello Faga

답변:


298
"Hello! world!".TrimEnd('!');

더 읽어보기

편집하다:

이 유형의 질문에서 내가 주목 한 것은 주어진 문자열의 마지막 문자를 제거하는 것이 좋습니다. 그러나 이것은 트림 방법의 정의를 충족시키지 못합니다.

트림-이 인스턴스의 시작과 끝에서 모든 공백 문자를 제거합니다.

MSDN- 트림

이 정의에서 문자열에서 마지막 문자 만 제거하는 것은 나쁜 해결책입니다.

"문자열에서 마지막 문자 다듬기"를 원하면 다음과 같이해야합니다.

확장 방법의 예 :

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); }

1
String의 끝에서 어떤 문자를 제거 할 것인지 항상 알고있는 한 더 좋습니다.
님로드 쇼리

1
안녕하세요 Vash, RegEx를 사용하는 솔루션에 대해 어떻게 생각하십니까? Thqr의 요청을 충족시키고 '!'를 제거 할 수 있습니다. "세계에서 온 숯!" 하나의 코드 행에식이 배치되는 모든 위치에있는 식입니다.
Marcello Faga

24
-1이 솔루션은 동일한 끝 문자를 모두 제거합니다! 예를 들어 "Hello !!!!!!!!" "Hello"로 이동하여 마지막 문자보다 더 많은 문자를 제거합니다.
Kugel

1
@ Kugel, 당신은 완전히 옳았으며, 왜 내 대답을 한 번 더 읽어야합니다. 설명을 위해 OP는 마지막 문자를 제거하는 방법을 묻는 것이 아니라 자르는 방법을 묻습니다.
Damian Leszczyński-Vash는

1
@Vash-어떻게 '작은 세상!'. TrimEnd ( '!') 방법을 사용하여 작은 따옴표를 제거합니까?
Steam

65
String withoutLast = yourString.Substring(0,(yourString.Length - 1));

14
yourString에 1 자 이상이 포함되어 있는지 확인하십시오.
님로드 쇼리

또한 문자열을 항상 제거하려는 문자로 끝나야합니다. EG : "Hello! World"는 "Hello! Worl"로 끝납니다.
Nathan Koop

9
if (yourString.Length > 1)
    withoutLast = yourString.Substring(0, yourString.Length - 1);

또는

if (yourString.Length > 1)
    withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);

... 공백이 아닌 문자를 끝에서 제거하려는 경우.


9
나는 의견없이 downvote를 상쇄하기 위해 투표했다. 사람들이 그렇게 할 때 싫어하십시오.
Jeff Reddy

2
TrimEnd()메소드 가 없기 때문일 수 있으며 , 존재하는 경우 Substring(..)짧은 문자열 에서 후속 호출이 실패 할 수 있습니다.
Rory

7
        string s1 = "Hello! world!";
        string s2 = s1.Trim('!');

끝없는 속성으로 작업하는 방법? 여기서 사용할 수 있습니까?
userAZLogicApps

1
Trim ()의 이름이 너무 잘못되었습니다. TrimStart () 및 TrimEnd ()와 마찬가지로 모든 선행 및 후행 문자 (복수)를 자릅니다.
안토니 부스


5
string helloOriginal = "Hello! World!";
string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));

5

문자열에서 마지막 문자 를 트리밍하는 또 다른 예 :

string outputText = inputText.Remove(inputText.Length - 1, 1);

확장 메서드에 넣고 null 문자열 등을 방지 할 수 있습니다.


3
string s1 = "Hello! world!"
string s2 = s1.Substring(0, s1.Length - 1);
Console.WriteLine(s1);
Console.WriteLine(s2);

2

이것을 사용할 수도 있습니다 :

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);
        }

    }

1

매우 쉽고 간단합니다.

str = str.Remove (str. 길이-1);


1

@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);
    }
}

0

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(",");          

0

이를 단순화하는 확장 클래스 예제 :-

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)

-5

'!'를 제거하려면 특정 표현의 문자 (귀하의 경우 "world")를 사용하면이 정규 표현식을 사용할 수 있습니다

string input = "Hello! world!";

string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);

// result: "Hello! world"

$ 1 특수 문자에는 일치하는 "world"표현식이 모두 포함되며 원래 "world!"를 대체하는 데 사용됩니다. 표현

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.