소개
이 랩에서는 주어진 문자열이 회문 (palindrome) 인지 확인하는 C++ 프로그램을 작성하는 방법을 배우게 됩니다. 회문은 뒤집어도 원래 문자열과 동일한 문자열입니다. 회문을 확인하기 위해 주어진 문자열을 뒤집어 원래 문자열과 비교합니다. 두 문자열이 동일하면 주어진 문자열은 회문이고, 그렇지 않으면 회문이 아닙니다.
이 랩에서는 주어진 문자열이 회문 (palindrome) 인지 확인하는 C++ 프로그램을 작성하는 방법을 배우게 됩니다. 회문은 뒤집어도 원래 문자열과 동일한 문자열입니다. 회문을 확인하기 위해 주어진 문자열을 뒤집어 원래 문자열과 비교합니다. 두 문자열이 동일하면 주어진 문자열은 회문이고, 그렇지 않으면 회문이 아닙니다.
먼저, 필요한 라이브러리를 포함하고 main() 함수를 정의합니다.
#include <iostream>
#include <string.h>
using namespace std;
int main() {
// code goes here
return 0;
}
다음으로, 사용자로부터 입력 문자열을 받아 문자 배열에 저장합니다.
char inputStr[100];
cout << "Enter a string: ";
cin >> inputStr;
strlen() 함수를 사용하여 입력 문자열의 길이를 계산합니다.
int strLength = strlen(inputStr);
다음으로, 역순 문자열을 위한 배열을 생성합니다.
char reverseStr[strLength];
이제 입력 문자열을 역순으로 만들고 새로 생성된 역순 문자열 배열에 저장합니다.
for(int i = 0; i < strLength; i++) {
reverseStr[i] = inputStr[strLength - 1 - i];
}
마지막으로, 입력 문자열이 회문 (palindrome) 인지 확인하기 위해 원본 문자열과 역순 문자열을 비교합니다.
if(strcmp(inputStr, reverseStr) == 0) {
cout << inputStr << " is a palindrome." << endl;
} else {
cout << inputStr << " is not a palindrome." << endl;
}
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char inputStr[100];
cout << "Enter a string: ";
cin >> inputStr;
int strLength = strlen(inputStr);
char reverseStr[strLength];
for(int i = 0; i < strLength; i++) {
reverseStr[i] = inputStr[strLength - 1 - i];
}
if(strcmp(inputStr, reverseStr) == 0) {
cout << inputStr << " is a palindrome." << endl;
} else {
cout << inputStr << " is not a palindrome." << endl;
}
return 0;
}
이 랩에서는 주어진 문자열이 회문 (palindrome) 인지 확인하는 C++ 프로그램을 작성하는 방법을 배웠습니다. 이제 이 프로그램을 사용하여 어떤 문자열이 회문인지 빠르게 확인할 수 있습니다.