관리 메뉴

Storage Gonie

(3) [C++, Java] 백준 No.10820 : 문자열 분석 본문

알고리즘/백준풀이5. 문자열

(3) [C++, Java] 백준 No.10820 : 문자열 분석

Storage Gonie 2019. 4. 25. 20:06
반응형

문제

풀이

# C++

#include <iostream>

using namespace std;

int main()
{
    string s;

    while (getline(cin, s)) // 공백을 포함하여 통째로 받는다.
    {
        int lower = 0;  //소문자 개수
        int upper = 0;  //대문자 개수
        int number = 0; //숫자 개수
        int space = 0;  //공백 개수

        for (char x : s)
        {
            if (x >= 'a' && x <= 'z')
                lower += 1;

            else if (x >= 'A' && x <= 'Z')
                upper += 1;

            else if (x >= '0' && x <= '9')
                number += 1;

            else if (x == ' ')
                space += 1;
        }
        cout << lower << ' ' << upper << ' ' << number << ' ' << space << endl;
    }
}

# Java

import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            int lower = 0;
            int upper = 0;
            int digit = 0;
            int space = 0;
            for (int i=0; i<s.length(); i++) {
                char c = s.charAt(i);
                if ('A' <= c && c <= 'Z') {
                    upper += 1;
                } else if ('a' <= c && c <= 'z') {
                    lower += 1;
                } else if ('0' <= c && c <= '9') {
                    digit += 1;
                } else if (c == ' ') {
                    space += 1;
                }
            }
            System.out.println(lower + " " + upper + " " + digit + " " + space);
        }
    }
}
반응형
Comments