문제 : Time Conversion
사용언어 : C++
문제 내용
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
Example
s = '12:01:00PM'
Return '12:01:00'.
s = '12:01:00AM'
Return '00:01:00'.
Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion has the following parameter(s):
- string s: a time in 12 hour format
Returns
- string: the time in 24 hour format
Input Format
A single string that represents a time in 12-hour clock format.
Constraints
- All input times are valid
Sample Input
07:05:45PM
Sample Output
19:05:45
내 풀이
문자열 다루기 문제였다.
이번문제도 기본 문제여서 번역기가 필요 없는 정도.
특정 문자열 가져오기 : substr()
stirng을 int자료형으로 : stoi()
문자열 비교 : compare()
문자열 다른 문자로 채우기 : replace()
int를 string자료형으로 : to_string()
특정 문자열 지우기 : erase()
string timeConversion(string s)
{
string sTimeFormat = s.substr(8,2);
int iTime = stoi(s.substr(0,2));
if(!sTimeFormat.compare("PM") && (0 < iTime && iTime < 12))
{
iTime += 12;
s.replace(0, 2, to_string(iTime));
}
else if(!sTimeFormat.compare("AM") && 12 == iTime)
{
s.replace(0, 2, "00");
}
s.erase(8, 2);
return s;
}
문자열 관련 함수
string의 부분 문자열 추출 / substr()
basic_string substr( size_type pos = 0, size_type count = npos ) const;
시작지점 pos와 길이 count를 인자값으로 넘겨주면
pos부터 count까지의 부분 문자열을 리턴한다.
string의 부분 문자열 지우기 / erase()
basic_string& erase( size_type index = 0, size_type count = npos );
시작지점 pos와 길이 count를 인자값으로 넘겨주면
pos부터 count까지 지운다.
string의 문자열 치환 / replace()
basic_string& replace( size_type pos, size_type count, const CharT* cstr );
시작지점 pos와 길이 count, 치환할 문자열을 인자값으로 넘겨주면
pos부터 count까지의 기존 문자열을 치환할 문자열로 치환한다.
string 문자열 비교 / compare()
int compare( const CharT* s ) const;
인자값으로 치환할 문자열을 넘겨주면
같은지 비교하여 같으면 0을 리턴한다.
ConditionResultReturn value
Traits::compare(data1, data2, rlen) < 0 | data1 is less than data2 | <0 | |
Traits::compare(data1, data2, rlen) == 0 | size1 < size2 | data1 is less than data2 | <0 |
size1 == size2 | data1 is equal to data2 | 0 | |
size1 > size2 | data1 is greater than data2 | >0 | |
Traits::compare(data1, data2, rlen) > 0 | data1 is greater than data2 | >0 |
string을 int 자료형으로 / stoi()
int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
인자값으로 문자열을 넣어주면 int자료형으로 변환된 숫자를 리턴한다.
stoi -> string to integer라는 뜻
만약 double형으로 변환하고 싶다면 stod,
long long 타입으로 변환하고 싶다면 stoll을 사용할 수 있다.
int를 string 자료형으로 / to_string()
string to_string( int value );
인자값으로 int자료형 value를 넘겨주면 string으로 변환된 문자열을 리턴한다.
참고
cppreference.com
Null-terminated strings: byte − multibyte − wide
en.cppreference.com