1. string
#include <iostream>
using namespace std;
int str_out(){
string a = "가나다";
cout << a[0] << endl;
cout << a[0] << a[1] << a[2] << endl;
cout << a << endl;
string b = "abc";
cout << b[0] << endl;
cout << b << endl;
return 0;
}
int str_method(){
string a = "love is";
a += " pain!";
a.pop_back();
a.pop_back();
cout << a << " : " << a.size() << "\n";
cout << char(*a.begin()) << "\n";
cout << char(*(a.end()-1)) << "\n";
a.insert(0, "test ");
cout << a << " : " << a.size() << "\n";
a.erase(0, 5);
cout << a << " : " << a.size() << "\n";
auto it = a.find("love");
if (it != string::npos){
cout << "포함되어 있다." << "\n";
}
cout << it << '\n';
cout << string::npos << '\n';
cout << a.substr(5, 2) << '\n';
return 0;
}
int main(){
str_out();
str_method();
}
Code language: PHP (php)
❯ g14 str.cpp
�
가
가나다
a
abc
love is pai : 11
l
i
test love is pai : 16
love is pai : 11
포함되어 있다.
0
18446744073709551615
is
Code language: CSS (css)
오버로딩된 메서드가 많기 때문에 매개변수의 종류와 수가 다를 수 있다.
str_out:cout << a[0] << endl;의 출력값이 이상한 이유는 영어는 알파벳이라 한 글자당 1바이트이지만 한글은 자음+모음+받침으로 한 글자가 이뤄지기 때문에 3바이트다.a.pop_back(): 문자열의 끝에 위치한 문자를 지운다.char(*a.begin())* :string.begin는 문자열의 첫번째 요소의iterator를 반환. 값에 접근하기 위해서는 역참조 연산자를 사용해야 한다.char(*(a.end()-1)):string.end는 문자열의 마지막 요소 + 1의iterator를 반환한다.a.insert(0, “test “);:a[0]에“test “를 삽입한다.insert(위치, 문자열)a.erase(0, 5);:a[0]에서a[5]까지 문자열을 지운다. (https://cplusplus.com/reference/string/string/erase/)
string& erase (size_t pos = 0, size_t len = npos); // 위치, 크기
iterator erase (const_iterator p);
iterator erase (const_iterator first, const_iterator last); // 시작, 끝
Code language: JavaScript (javascript)
auto it = a.find(”love”);: 문자열에서 특정 문자열"love"를 찾아서 위치를size_t로 반환. 존재하지 않는 문자열인 경우string::npos를 반환한다.string::npos는size_t타입의 최댓값이다. (https://cplusplus.com/reference/string/string/find/)
size_t find (const string& str, size_t pos = 0) const noexcept;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_type n) const;
size_t find (char c, size_t pos = 0) const noexcept;
Code language: JavaScript (javascript)
a.substr(5, 2):a[5]에서부터 2개의 문자를 추출한다. (https://cplusplus.com/reference/string/string/substr/)- 또한 substr(pos)처럼 입력하면 pos부터 끝까지 문자열을 반환한다.
string substr (size_t pos = 0, size_t len = npos) const; // 위치, 크기
Code language: JavaScript (javascript)
가. atoi()
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string s = "1";
string s2 = "amumu";
cout << atoi(s.c_str()) << endl;
cout << atoi(s2.c_str()) << endl;
return 0;
}
/*
1
0
*/
Code language: PHP (php)
만약 입력받은 문자열이 “문자”라면 0을 반환. “숫자”면 숫자를 반환합니다.
나. reverse()
#include <iostream>
#include <algorithm> //std::reverse
using namespace std;
int main(){
string a = "It's hard to have a sore leg";
reverse(a.begin(), a.end());
cout << a << endl;
reverse(a.begin(), a.end());
cout << a << endl;
reverse(a.begin() + 5, a.end());
cout << a << endl;
return 0;
}
/*
gel eros a evah ot drah s'tI
It's hard to have a sore leg
It's gel eros a evah ot drah
*/
Code language: PHP (php)
reverse(시작 이터레이터, 끝 이터레이터): 시작 ~ 끝 문자열을 순서를 뒤집는다.
다. split()
// #include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
vector<string> splitMetod (string input, string delimiter){
vector<string> ret;
auto pos = 0;
string token = "";
while((pos = input.find(delimiter)) != string::npos){
token = input.substr(0, pos);
ret.push_back(token);
input.erase(0, pos + delimiter.length()); //erase(위치, 크기)
}
ret.push_back(input);
return ret;
}
int main(void){
string str = "hello world go to hell";
string deli = " ";
vector<string> splited_str = splitMetod(str,deli);
for(string word : splited_str ) cout << word << "\n";
return 0;
}
/*
hello
world
go
to
hell
*/
Code language: PHP (php)
C++의 string은 따로 split 함수를 지원하지 않는다.
그래서 직접 만들어서 사용해야 한다.
find, substr, push_back, erase을 사용해서 구현한다.
delimiter 전까지 문자열을 추출해서 문자열 벡터에 집어넣는다.
그리고 문자열의 시작부터 delimiter의 끝까지 지운다.
delimiter가 더 이상 없을 때까지 반복하고 더이상 없으면 남은 문자열을 벡터에 추가하고 벡터를 반환한다.
while ((pos = input.find(delimiter)) != string::npos) {
token = input.substr(0, pos);
ret.push_back(token);
input.erase(0, pos + delimiter.length());
}
ret.push_back(input);
Code language: PHP (php)
이 부분만 기억하고 있으면 된다.
8월 11일 추가
다. append()
- string 뒤에 string 붙이는 방법
string str1 = "hello", str2 = "world";
str1.append(str2);
Code language: JavaScript (javascript)
- 반복문을 사용하지 않고 n개의 “A”를 출력하는 방법
string str;
str.append(n, 'a') //str 뒤에 n개의 'a'를 이어 붙여줌
cout << str;
Code language: JavaScript (javascript)
그외에도 다양한 방식으로 문자열에 문자열을 추가하기 위해서 많이 활용함.
8월 11일 추가
다. to_string()
- string으로 변환
#include<string>
string to_string (int num);
string to_string (long num);
string to_string (long long num);
string to_string (unsigned num);
string to_string (unsigned long num);
string to_string (unsigned long long num);
string to_string (float num);
string to_string (double num);
string to_string (long double num);
Code language: HTML, XML (xml)