언어 공부/C++
string-1
세희홍
2022. 6. 22. 18:17
문자열
1. c 스타일: 함수, char array[], char* array
2. c++스타일: 클래스, 객체, 메서드, string
복사하기
1. c 스타일
#pragma warning(disable:4996)
#include <iostream>
#include <cstring> //c언어의 string.h
using namespace std;
int main() {
char s[] = "Ace";
int len = strlen(s); // string 길이
char* t = new char[len + 1]; // 동적할당
strcpy(t, s); //string copy
cout << "source: " << s << endl; // Ace
cout << "target: " << t << endl; // Ace
delete[] t;
t = nullptr;
return 0;
}
2. c++ 스타일
int main() {
string s = "Ace";
string t;
t = s; // 연산자 오버로딩
cout << "length: " << s.size() << endl; // 3
cout << "source: " << s << endl;
cout << "target: " << t << endl;
return 0;
}
문자열 합치기 & 비교하기
1. c스타일
#pragma warning(disable:4996)
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s1[20] = "Ece";
char s2[] = "Nice";
strcat(s1, s2); // s1으로 합치기
if (strcmp(s1, "AceNice") == 0) // 문자열이 일치하면 0을 리턴
cout << "같음\n";
cout << strcmp("Diff", s1); // 앞쪽 인수가 크면 1, 작으면 -1을 리턴
return 0;
}
const char* str1 = "hello alice.";
const char* str2 = "hello john.";
const char* str3 = "hello betsy.";
const char* str4 = "hello betsy.";
cout << "str1과 str2 비교하기: ";
cout << strcmp(str1, str2) << endl; // -1
cout << "str2와 str3 비교하기: ";
cout << strcmp(str2, str3) << endl; // 1
cout << strcmp(str3, str4) << endl; // 0
cout << "str1과 str2의 앞 5문자만 비교하기: ";
cout << strncmp(str1, str2, 5); // 0
char str1[20] = "This is ";
//const char* str1 = "This is "; 고정시키면 합칠 수 없으므로 에러
const char* str2 = "a string.";
strcat(str1, str2);
cout << "str1: " << str1 << endl; // str1: This is a string.
2. c++스타일
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Ace";
string s2 = "Nice";
s1 = s1 + s2; // 결합
if (s1 == "AceNice") // 문자열이 일치하면 0을 리턴
cout << "같음\n";
if (s1 != "Diff") // 문자열이 일치하면 0을 리턴
cout << "다름\n";
return 0;
}
C 문자열 생성
char str[] = "ABCD";
char* p = str;
상수 포인터가 아닌 변수. 값을 수정할 수 있다.
const char str[] = "ABCD";
const char* p = str;
상수 포인터이므로 값을 수정할 수 없다. read-only
const char* str = "ABCD";
문자열 리터럴을 사용해서 문자열 생성. "ABCD"의 맨 앞의 주소를 str이 받아서 사용. 읽기전용으로 특정 위치의 글자를 꺼내올 수 있다. const 꼭 사용해야 한다.
- 간단한 형태의 초기화와 문자열 리터럴
char str1[] = "Hello"; // 간단한 형태의 초기화
const char str2[] = "Hello"; // 간단한 형태의 초기화
const char* str3 = "Hello"; // 문자열 리터럴. 메모리에 올라간 문자열에 대한 포인터
- 힙 메모리에 생성
char* str = new char[3]; // 두 문자를 가질 수 있는 상수가 아닌 문자열
const char* str = new char[3]; // 두 문자를 가질 수 있는 상수 문자열
const char* str = new char[3]; // 생성
delete[] str; // 파괴