-- 예전 기록/BOJ

[ BOJ ] 9086 : 문자열 ( BRONZE 5 ) / C, C++, Python, Java

rejo 2023. 9. 23. 14:58

문제

문자열을 입력으로 주면 문자열의 첫 글자와 마지막 글자를 출력하는 프로그램을 작성하시오.

입력

입력의 첫 줄에는 테스트 케이스의 개수 T(1 ≤ T ≤ 10)가 주어진다. 각 테스트 케이스는 한 줄에 하나의 문자열이 주어진다. 문자열은 알파벳 A~Z 대문자로 이루어지며 알파벳 사이에 공백은 없으며 문자열의 길이는 1000보다 작다.

출력

각 테스트 케이스에 대해서 주어진 문자열의 첫 글자와 마지막 글자를 연속하여 출력한다.

풀이 과정

인덱싱을 이용해 첫 글자와 마지막 글자를 출력한다.

C

#include <stdio.h>
#include <string.h>

int main(void) {
    int t; scanf("%d", &t);
    char str[1001];
    while (t--) {
        scanf("%s", str);
        printf("%c%c\n", str[0], str[strlen(str)-1]);
    }
    return 0;
}

C++

#include <iostream>
#include <string>
using namespace std;

int main(void) {
    int t; cin >> t;
    string str;
    while (t--) {
        cin >> str;
        cout << str.at(0) << str.at(str.length() - 1) << endl;
    }
    return 0;
}

Python

import sys
input = sys.stdin.readline

t = int(input().rstrip())
for _ in range(t):
    string = input().rstrip()
    print(string[0] + string[-1])

Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        String s;
        sc.nextLine();
        for (int i = 0; i < t; i++) {
            s = sc.nextLine();
            System.out.println(s.charAt(0) + "" + s.charAt(s.length() - 1));
        }
    }
}