본문 바로가기
알고리즘/프로그래머스

[C++] (대소문자 범위) 문자열안에 문자열, 숨어있는 숫자의 덧셈 (1)

by parkkingcar 2023. 5. 16.

 

 

문자열에 문자열

문자열 str, str2가 매개변수로 주어지면 str2가 str1에 포함되는지 판별하는 문제입니다.

 

 

string의 find() 함수를 이용합니다. str2 가 str1 안에 포함된다면 string::npos을 반환합니다.

#include <string>
#include <vector>

using namespace std;

int solution(string str1, string str2) {
    if (str1.find(str2) != string::npos){
    	return 1;
    }
    return 2;
}

 

 

 

 

 

 

 

숨어있는 숫자의 덧셈 (1)

문자열 my_string이 매개변수로 주어질 때, my_string안의 자연수들의 합을 반환하는 문제입니다.

 

 

문자의 아스키코드 값으로 접근할 수 있는 문제입니다.

#include <string>
#include <vector>

using namespace std;

int solution(string my_string) {
    int answer = 0;
    for(int i = 0 ; i < my_string.size(); i++){
        if(my_string[i] > 47 && my_string[i] < 58) 
            answer+=my_string[i]-'0';
    }
    return answer;
}

 

answer[0]의 요소가 문자 '1'이라면 아스키 코드값은 49가 되며, 문자 '0'의 경우는 48이 됩니다.

49와 48의 차는 1로 정수형 1을 얻을 수 있습니다. 또한 문자 '9'의 값은 57로, '0'의 아스키 코드값 48과의 차는 9가 됩니다.

 

// stoi 사용시 
        	//string charString(1, my_string[i]);
            //int a = stoi(charString);


//각 문자별 아스키 코드값 범위

        if (input[count] >= 65 && input[count] <= 90) // 대문자

        else if (input[count] >= 97 && input[count] <= 122) // 소문자

        else if (input[count] >= 48 && input[count] <= 57) // 숫자
       
        else if (input[count] >= '0' && input[count] <= '9') // 숫자
        
// 대문자 -> 소문자 변환은 +32 또는 toupper()
// 소문자 -> 대문자 변환은 -32 또는 tolower()

// string 비교
str1 == string(1,str2[0])

 

댓글