[C# 문법] string 배열에서 공백 문자 제거하기

안녕하세요.

 

오늘은 C# 문법에서 string[] 배열에서 저장되어 있는 공백 문자를 제거하는 방법에 대해서 알려 드리려고 합니다.

 

프로그램을 만들던 중에, string[] 배열을 사용하다가 안에 공백 문자가 있어서 어떻게 하면 제거할 수 있는지 찾다가 알게 되어 공유하고자 포스팅 하게 되었습니다.

 

그럼 바로 예제 코드를 작성해 보도록 하겠습니다.

 

예제 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = $"안녕하세요; 범범 조조; 입니다. 만나서; 반갑습니다.;";
            string[] arr = str.Split(';');
 
            for(int idx = 0; idx < arr.Length; idx++)
            {
                Console.WriteLine($" {idx} 번째 값 = {arr[idx].ToString()}");
            }
 
            Console.WriteLine();
            Console.WriteLine();
 
            //공백제거
            arr = arr.Where(x => !string.IsNullOrEmpty(x)).ToArray();
 
            for (int idx = 0; idx < arr.Length; idx++)
            {
                Console.WriteLine($" {idx} 번째 값 = {arr[idx].ToString()}");
            }
        }
    }
}
 
cs
실행결과

위와 같이 Linq를 이용하여 공백문자를 제거할 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY