Koala - 6기/기초 알고리즘 스터디

[백준/Python] 2743번: 단어 길이 재기

hoeunwang 2022. 3. 27. 08:51
#include <iostream>
#include <string>
using namespace std;
string str;

int main(void) {

	cin >> str;
	cout << str.size();
    
    return 0;
}​

https://www.acmicpc.net/problem/2743

 

2743번: 단어 길이 재기

알파벳으로만 이루어진 단어를 입력받아, 그 길이를 출력하는 프로그램을 작성하시오.

www.acmicpc.net


문제 해석


문자열을 입력받은 후 그 길이를 카운트 해서 출력해주는 문제이다.


코드


#include <iostream>
#include <string>
using namespace std;
string str;
int cnt = 0;

int main(void) {
	cin >> str;
    
	for (int i = 0; i < str.size(); i++) {
		cnt++;
	}
    
	cout << cnt;

	return 0;
}
#include <iostream>
#include <string>
using namespace std;
string str;

int main(void) {

	cin >> str;
	cout << str.size();
    
    return 0;
}

문제 풀이


 문자열을 입력받은 후, 그 문자열의 끝까지 반복문을 돌려서 문자열의 길이를 카운트 해주는 방법이 있다.
 하지만, 구지 카운트 해주는 변수를 만들지 않아도 #include <string> 안에 있는 문자열의 길이를 출력해주는 .size()를 활용하면 바로 문제를 풀어낼 수 있다.