문자열의 내용과 식별성
Coddy의 C# 개발자를 위한 C 코스 레슨. 48개 중 15번째.
C#에서는 문자열 내용이 같은지 비교하도록 string == 연산자가 오버로드되어 있습니다. C에서 char 포인터의 == 연산자는 주소를 비교하므로, 널 종료 문자열의 내용을 비교하려면 strcmp를 사용하세요. 이는 구문 수준에서 발생하기 특히 쉬운 포팅 실수입니다.
문자열 내용을 비교할 때는 strcmp를 사용하세요. 포인터 동등성 검사는 주소를 비교합니다. strcmp의 부호만 이식성이 있습니다.
C# 예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Main(){
string a=new string(new[]{'c','a','t'}),b="cat";Console.WriteLine(a==b?"true":"false");
}
}
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을 반환하세요. 대소문자를 구분하며 공백을 제거하지 않습니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금 상태의 main.c에서 함수를 직접 호출하므로 선언된 공개 API와 호환되도록 유지하세요. 다른 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 컴파일러