-
[C++] 문자열이 회문인지 알아보는 프로그램C++/문제풀이 2022. 6. 15. 12:44
Power C++ p.257
문자열이 회문인지 알아보는 프로그램
#include <iostream> #include <cstring> using namespace std; // p.296 16번) // 문자열이 회문인지 알아보는 프로그램 // 1. i번째 원소와 length - 1 - i이 같은지 비교 int main(){ cout << "\n\n문자열이 회문인지 알아보는 프로그램" << endl; char sentence[81]; cout << "문장을 입력하세요: "; // cin >> sentence; //단어 입력 OK, 문장입력 => 공백 문자 처리 불가(cin 객체) cin.getline(sentence, 81); //1. 문자열 맨 끝의 길이: 문자열의 length 구하기 int length = strlen(sentence); cout << "입력된 문자열: " << sentence << endl; bool pal = true; for(int i = 0; i<length/2; i++){ //같지 않은 원소 발견? => 바로 종료, false 확정 if (sentence[i] != sentence [length - i -1]){ pal = false; break; } } if(pal == true) cout << "네, 회문입니다." << endl; else cout << "아니오, 회문이 아닙니다. " << endl; return 0; }
실행 결과
Key Point
1. 회문이 아닌 경우
sentence[i] != sentence [length - i -1]
'C++ > 문제풀이' 카테고리의 다른 글
[C++] Date, Employee.cpp (클래스의 포함 관계) (0) 2022.06.30 [C++] 질문 후 답변이 긍정이면 1, 부정이면 0 반환하는 함수 (0) 2022.06.15 [C++] 문자열 안에 있는 영단어의 개수 계산 (0) 2022.06.15 [C++] 문자열을 입력받아서 문자열에 포함된 모든 공백 문자를 삭제하는 프로그램 (0) 2022.06.15 [C++] 두 행렬의 곱 구하기(3x3) (0) 2022.06.14