문자열과 종료 문자
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 14번째.
C++ std::string은 바이트, 크기, 저장 공간을 관리하며 내장된 0 바이트를 포함할 수 있습니다. C의 strlen은 첫 번째 0 종결자에서 멈춥니다. 바이트 수는 어느 쪽도 자동으로 유니코드 문자 수를 나타내지 않습니다.
C 문자열은 0 바이트에서 끝납니다. 용량에는 종결자를 위한 공간이 포함되지만, strlen은 그 앞에 있는 바이트를 셉니다.
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 s="cat";std::cout<<s.size()<<"\n";
}
C++ 출력:
3C 예제
#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 s[]="cat";printf("%zu:%zu\n",strlen(s),sizeof s);
return 0;
}
C 출력:
3:4챌린지
쉬움입력은 128바이트보다 짧은 ASCII 한 줄이며, 비어 있을 수도 있습니다. 끝의 널 문자와 입력 개행 문자를 제외한 바이트 길이를 반환하세요.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 공개된 잠금 상태의 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("%zu\n",text_length(text));return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러