언어/C++

[Programmers/ c++] Level1. 문자열 내 p와 y의 개수

연나연 2024. 2. 1. 00:55
<목차>

1. 문제설명
2. 풀이정리
3-1. string을 대문자로 변경하는 법
3-2. string을 소문자로 변경하는 법
4. find()함수를 이용하여 string에서 특정 문자 개수 찾기
       4-1.문자열 검색
       4-2. find()함수를 이용하여 string에서 특정 문자 개수 찾기
              4-2-1. string::npos
5. 코드

1. 문제설명

 

2. 풀이정리

1. string s를 전체 소문자(또는 대문자)로 변경한다.
2. p의 개수를 계산한다.
3. y의 개수를 계산한다.
4. answer이 true인지 false인지 계산한다.
    - pCount와 yCount가 모두 0인 경우: true
    - pCount == yCount 인 경우: true
    - pCount != yCount 인 경우: false

 

3-1. string을 대문자로 변경하는 법

topper함수를 이용한다.
이 함수는 문자열이 아닌 문자 하나하나를 바꿔주는 함수이기에, string 전체를 대문자로 변경하고 싶을 때에는 for문을 사용한다. 아래 예시를 참고하세용

std::toupper(int ch) 

#include <iostream>
#include <string>

using namespace std;

int main() {

    string str = "Hello World";

    for (int i = 0; i < str.size(); i++) {
        str[i] = toupper(str[i]);
    }

   cout << str << endl;

    return 0;
}​
출력: HELLO WORLD

 

3-2. string을 소문자로 변경하는 법

tolower함수를 이용한다.
이 함수는 문자열이 아닌 문자 하나하나를 바꿔주는 함수이기에, string 전체를 대문자로 변경하고 싶을 때에는 for문을 사용한다. 아래 예시를 참고하세용

std::tolower(int ch)

#include <iostream>
#include <string>

using namespace std;

int main() {

    string str = "Hello World";

    for (int i = 0; i < str.size(); i++) {
        str[i] = tolower(str[i]);
    }

   cout << str << endl;

    return 0;
}​

출력: hello world

 

4. find()함수를 이용하여 string에서 특정 문자 개수 찾기

       4-1.문자열 검색

+find(c: char): int 문자열에서 문자 c가 발견되는 최초 인덱스를 반환
+find(c: char, index: int): int index부터 찾아서 문자 c가 발견되는 최초 인덱스를 반환
+find(s: string): int 문자열에서 문자열 s가 발견되는 최초 인덱스를 반환
+find(s: string, index: int): int index부터 찾아서 문자열 s가 발견되는 최초 인덱스를 반환

 

       4-2. find()함수를 이용하여 string에서 특정 문자 개수 찾기

find() 함수는 최초 발견된 위치를 반환하기 때문에 문자열에서 'p'가 몇 개 있는지 찾고싶으면 이렇게 사용하면 된다.
 소문자 p의 개수
    string s1("How many p are there");
    while (s1.find('p', idx) != string::npos) {
        idx = s1.find('p', idx);
        pCount++;
    }​

 

              4-2-1. string::npos

string::npos 는 C++의 string 클래스에서 제공하는 상수로, 문자열에서 찾는 값이 없을 때 반환되는 값


s1.find('p', idx)는 문자열s1에서 인덱스idx부터 시작하여 문자 'p'를 찾는 것을 의미합니다.
만약 문자 'p'가 없다면 string::npos를 반환한다.


즉, string::npos 는 주로 문자열에서 특정 문자나 부분 문자열을 찾는 동작에서 찾는 내용이 없을 때의 반환값으로 사용된다.

5. 코드

내가 작성한 코드는 다음과 같다!
#include <iostream>
#include <string>

using namespace std;


bool solution(string s)
{
	// 변수 정의
	int pCount = 0, yCount = 0;
	bool answer;

	// 문자열 s를 소문자로 변경한다
	for (int i = 0; i < s.size(); i++) {
		s[i] = tolower(s[i]);
	}

	// 문자 p의 개수를 구한다
	int idx = 0;
	while (s.find('p', idx) != string::npos) {
		idx = s.find('p', idx) + 1;
		pCount++;
	}

	// 문자 y의 개수를 구한다
	idx = 0;
	while (s.find('y', idx) != string::npos) {
		idx = s.find('y', idx) + 1;
		yCount++;
	}

	// answer이 true인지 false인지 구한다
		// pCount와 yCount가 0일 경우
	if (pCount == 0 && yCount == 0) {
		answer = true;
	}
	else {
		// pCount != yCount 일 경우
		if (pCount == yCount) {
			answer = true;
		}
		// pCount = yCount 일 경우 
		else if (pCount != yCount) {
			answer = false;
		}
	}

    return answer;
}

int main() {

    // 변수 정의
    string s;

    // 사용자로부터 문자열 s를 입력받는다
    cin >> s;

    // solution함수 호출
    bool answer = solution(s);

    // answer을 출력한다
    cout << boolalpha << answer;

    return 0;
}

pass !
근데 다른 사람들 풀이 보니까, 내 코드가 터무니없이 긴 것이다..
물론 코드가 짧다고 무조건 좋은건 아니지만 효율성이 너무 떨어지는 듯한 ..ㅠ.ㅠ
더 분발하자~! 아자자아자자