백준 1152 단어의 개수

Console Programming/C# Console 2020. 4. 2. 16:56

처음에 작성한 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
 
namespace _1152
{
    class Program
    {
        static void Main(string[] args)
        {
            var str = Console.ReadLine();
 
            var str2 = str.Trim(' ');
 
            var arr = str2.Split(' ');
 
            Console.WriteLine(arr.Length);
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

입력으로 공백문자가 들어오면 1이 찍히는 문제가 있었다.

 

 

수정된 코드

 

공백문자가 있으면 count를 세고, 마지막에 단어갯수에서 공백문자의 수를 빼준다.

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
using System;
 
namespace _1152
{
    class Program
    {
        static void Main(string[] args)
        {
            var str = Console.ReadLine().Trim();
 
            var words = str.Split();
            int count = 0;
            foreach(var a in words)
            {
                if(string.IsNullOrEmpty(a))
                {
                    count++;
                }
            }
 
            Console.WriteLine(words.Length - count);
 
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 

'Console Programming > C# Console' 카테고리의 다른 글

백준 2941 크로아티아 알파벳  (0) 2020.04.02
백준 2908 상수  (0) 2020.04.02
백준 10872 팩토리얼  (0) 2019.12.20
4948 베르트랑 공준  (0) 2019.12.04
1929 소수 구하기 에라토스테네스의 체  (0) 2019.12.04
: