[C++] string 뿌시기

kkily·2024년 4월 11일
0

[알고리즘]

목록 보기
102/102

substr

string.substr()
#include <string>
string str;
str.substr(pos, len);
  • pos 인덱스부터 시작해 len 길이만큼의 문자열을 반환
  • pos는 기본값으로 0을 가짐, len은 기본값으로 npos 가짐
  • pos에서 시작해서 len 길이만큼의 문자열을 가져온다고 했을 때 문자열의 범위를 벗어난다면 마지막 문자까지만 리턴한다.

🖥️ 예제 코드

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "ABCDEFG";

    cout << str.substr() << endl; //ABCDEFG
    cout << str.substr(1) << endl; //BCDEFG
    cout << str.substr(2, 3) << endl; //CDE
    cout << str.substr(6, 100) << endl; G
}

인수로 아무 것도 전달하지 않으면 원본 문자열 그대로 반환
인수로 시작 인덱스만 전달한다면 해당 인덱스 ~ 문자열 마지막까지 반환
지정된 범위가 원본 문자열 길이를 벗어나면 오류 없이 문자열 마지막까지만 반환

sstream

1) stringstream

입출력 스트림: 입력 스트림, 출력 스트림을 모두 할 수 있다.

2) istringstream

입력 스트림
문자열을 공백과 '\n'을 기준으로 여러 개의 다른 형식으로 차례대로 분리할 때 편리하다.
반복문 실행 시 자료형에 맞는 데이터가 없을 때까지 실행된다.

🖥️ 예제 코드

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	istringstream iss("test\n123 aaa 456");
	string s1, s2;
	int i1, i2;
	iss >> s1 >> i1 >> s2 >> i2; // 문자열을 파싱하고 변수형에 맞게 변환한다.

	cout << s1 << endl; // test
	cout << i1 << endl; // 123
	cout << s2 << endl; // aaa
	cout << i2 << endl; // 456
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
 
 int main() {
    string str1 = "1D2S#10S";
    string str2 = "1111DAWV2S#10S";
     
    istringstream iss1(str1);
    istringstream iss2(str2);
    int num1, num2;
    while (iss1 >> num1) cout << num1 << " ";
    cout << endl;
    while (iss2 >> num2) cout << num2 << " ";
    cout << endl;
    
    istringstream iss3(str1);
    istringstream iss4(str2);
    char ch1, ch2;
    while (iss3 >> ch1) cout << ch1 << " ";
    cout << endl;
    while (iss4 >> ch2) cout << ch2 << " ";
    cout << endl;
}

// 실행 결과
// 1 
// 1111 
// 1 D 2 S # 1 0 S 
// 1 1 1 1 D A W V 2 S # 1 0 S

3) ostringstream

출력 스트림
문자열을 조립하거나 특정 형식을 문자열로 변환하기 위해 사용한다.

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	ostringstream oss;
	string s1 = "abc", s2 = "gjw";
	int i1 = 19234;
	double d1 = 3.591;
	oss << s1 << "\n" << i1 << "\n" << s2 << "\n" << d1; // 문자열을 붙인다.
	cout << oss.str(); // 문자열을 꺼낸다.
}

// 실행 결과
// abc
// 19234
// gjw
// 3.591

4) str(), clear()

str(string s): stringstream에 저장된 문자열을 바꾼다. 이때 s가 "" 일 경우 문자열을 삭제하는 것과 같다.
str(): stringstream이 저장하고 있는 문자열의 복사본을 반환한다.
clear(): stringstream 재사용하려면 clear()를 실행해야 한다. 이때 저장된 문자열이 삭제되진 않는다.

5) get(), unget()

get(): 커서를 뒤로 옮기면서 값을 반환한다.
unget(): 커서를 앞으로 다시 옮긴다.

string str = "123abc";

// get()
stringstream ss1;
ss1.str(str);
cout << ss1.get() - '0'; // 1: -'0' 안해주면 아스키코드값이 나옴
cout << ss1.get() - '0'; // 2

// unget()
stringstream ss2;
ss2.str(str);
char ch;
ss2 >> ch; // 1
ss2 >> ch; // 2
ss2.unget();
ss2 >> ch; // 1

6) getline()

문자열을 공백이나 '\n'이 아닌 다른 문자를 기준으로 분리하고 싶을 때 사용한다.

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	string str = "gkg|qiew|789", token;
	stringstream ss(str);
	while (getline(ss, token, '|')) {
		cout << token << endl;
	}
}

// 실행 결과
// gkg
// qiew
// 789

참고 블로그 1

참고 블로그 2

profile
낄리의 개발 블로그╰(*°▽°*)╯

0개의 댓글

Powered by GraphCDN, the GraphQL CDN