문자열의 내용과 동일성
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 15번째.
C++의 std::string은 내용 비교를 위해 == 연산자를 오버로드합니다. C++와 C 모두에서 원시 char 포인터는 주소를 비교합니다. 문자열 객체 비교 코드를 옮길 때 ==를 무작정 유지하지 말고 strcmp를 사용하세요.
문자열 내용 비교에는 strcmp를 사용하세요. 포인터 동등성은 주소를 확인합니다. strcmp의 부호만 이식성이 있습니다.
C++ 예제
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
int main(){
std::string a="cat",b="cat";std::cout<<std::boolalpha<<(a==b)<<"\n";
}
C++ 출력:
trueC 예제
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
char a[]="cat",b[]="cat";printf("%d\n",strcmp(a,b)==0);
return 0;
}
C 출력:
1챌린지
쉬움입력은 ASCII 한 줄입니다. 정확히 yes이면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 대소문자를 구분하며 공백을 제거하지 않습니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 공개 API 선언은 표시된 잠금된 main.c에서 직접 호출할 수 있도록 호환성을 유지하세요. 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 확인하지 않는 한, 모든 숫자 작업 입력값은 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 드라이버가 표시된 경우 입력 구문 분석과 출력을 처리합니다.
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){char text[128]="";if(fgets(text,sizeof text,stdin))text[strcspn(text,"\n")]=0;printf("%d\n",is_yes(text));return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러