C#에서 여러 공백을 단일 공백으로 바꾸는 방법은 무엇입니까?

王林
풀어 주다: 2023-09-18 08:53:02
앞으로
1592명이 탐색했습니다.

如何在 C# 中将多个空格替换为单个空格?

C#에서는 여러 공백을 단일 공백으로 바꾸는 여러 가지 방법이 있습니다.

String.Replace - 지정된 유니코드 문자 또는 문자열의 모든 항목이 현재 문자열의 내용을 지정된 다른 유니코드 문자 또는 문자열로 바꾸는 새 문자열을 반환합니다.

Replace(String, String, Boolean, CultureInfo)

String.Join 각 요소 또는 멤버 사이에 지정된 구분 기호를 사용하여 지정된 배열의 요소 또는 컬렉션의 멤버를 조인합니다.

Regex.Replace - 지정된 입력 문자열에서 일치하는 문자열을 지정된 대체 문자열의 정규식 패턴으로 바꿉니다.

정규 표현식을 사용한 예 -

Example

Live Demonstration

using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   class Program{
      public static void Main(){
         string stringWithMulipleSpaces = "Hello World. Hi Everyone";
         Console.WriteLine($"String with multiples spaces:
            {stringWithMulipleSpaces}");
         string stringWithSingleSpace = Regex.Replace(stringWithMulipleSpaces, @"\s+", " ");
         Console.WriteLine($"String with single space: {stringWithSingleSpace}");
         Console.ReadLine();
      }
   }
}
로그인 후 복사

Output

위 프로그램의 출력은

String with multiples spaces: Hello World. Hi Everyone
String with single space: Hello World. Hi Everyone
로그인 후 복사
로그인 후 복사

입니다. 위의 Regex.Replace 예에서는 추가 공백과 단일 공백으로 바꾸기

string.Join을 사용한 예 -

Example

Live Demonstration

using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         string stringWithMulipleSpaces = "Hello World. Hi Everyone";
         Console.WriteLine($"String with multiples spaces:
         {stringWithMulipleSpaces}");
         string stringWithSingleSpace = string.Join(" ",
         stringWithMulipleSpaces.Split(new char[] { ' ' },
         StringSplitOptions.RemoveEmptyEntries));
         Console.WriteLine($"String with single space: {stringWithSingleSpace}");
         Console.ReadLine();
      }
   }
}
로그인 후 복사

Output

위 프로그램의 출력은

String with multiples spaces: Hello World. Hi Everyone
String with single space: Hello World. Hi Everyone
로그인 후 복사
로그인 후 복사

위에서 Split 메소드를 사용하여 여러 공간에 텍스트를 넣고, 나중에 Join 메서드를 사용하여 분할된 배열을 단일 공백으로 결합합니다.

위 내용은 C#에서 여러 공백을 단일 공백으로 바꾸는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!