string s = "Hello World";//s라는 문자열 객체를 생성, s에 객체를 복사(2단계)
string s("Hellow World"); //문자열 생성자 사용
string s; // 빈 문자열(empty string)
string
"+" append(string s) : string + s
"+" append (string s, int a, int b) : string + s의 a번째 부터 b개
"+" append (string s, int a) : string + s의 처음부터 a개
"+" append(int a, char c) : string + c를 a개
string s1("Hello");
s1.append(" World"); //Hello World
string s2("Welcome");
s2.append(" to C++", 0, 5); //Welcome to C -> 0번 부터 5개 추가
s2.append(" to C++",3,4); // Welcome to C C++ -> 3번째부터 4개 추가
string s3("Welcome");
s3.append(" to C++",7); // Welcome to C++ -> 처음부터 7개 추가
string s4("Hello");
s4.append(8,'O'); //HelloOOOOOOOO -> (int,char)-> char을 int 개 추가
string
"+" assign(string s) : s-> string 대입
"+" assign(string s, int a, int b) :s의 a번째 부터 b개 -> string
"+" assign(string s, int a) : s의 처음에서 a번째 까지 -> string
"+" assign(int a, char b) : a개의 b를 -> string
string s1("Hello");
s1.assign(" World"); //World
string s2("Welcome");
s2.append(" to C++", 0, 5); //to C -> 0번 부터 5개 대입
s2.append(" to C++",3,4); //C++ -> 3번째부터 4개 대입
string s3("Welcome");
s3.append(" to C++",7); // to C++ -> 처음부터 7개 대입
string s4("Hello");
s4.append(8,'O'); //OOOOOOOO -> 'O' 8개 대입
- at(index) : 특정 인덱스에서 문자 검색
- clear() : 문자열을 제거
- erase(index, n) : 문자열의 일부 삭제(index 부터 n개)
- empty() : 문자열이 비었는지 확인
string s1("Hello World");
cout << s1.at(3) <<endl; //'l'
s1.erase(5,6); //5번째 부터 6개 삭제
cout<<s1<<endl;//Hello
s1.clear() ;//문자열 삭제
cout << s1.empty()<<endl;//1->참(비어있음)
- length() : 문자열의 길이
- size() : 문자열의 크기 -> length와 동일
- capacity() : 문자열의 용량
string s1("Hell0 World");
cout << s1.length() <<endl; //11 string의 길이
cout << s1.size() << endl; //11
cout << s1.capacity()<<endl; //15
s1.clear();
cout<<s1.capacity()<<endl; //15
cout<<s1.empty()<<endl; //1
s1이 생성될 때 용량은 15로 설정되며 문자열을 clear()을 이용해 지운 이후에도 용량에도 변화가 없음을 볼 수 있다.
C++에서 string은 불변 객체이다.