c++/ 자료구조&알고리즘 개념 복습하기 - 7 / 문자열 다루기

한창희·2022년 1월 31일
0

< 특정 문자열 찾기 >

  • find 사용
    ex> 공백이 처음으로 위치한 인덱스 반환
    = str.find(' ');


만약 공백이 존재하지 않을 경우 ~~ -1를 반환한다~~!!
= 주의!!!!!!
https://kamang-it.tistory.com/437

  • -1이 아닌 큰 수가 반환된다
  • std::string.find() 함수에서 찾고자 하는 문자열이 없으면 'string::npos'를 반환하게 된다.


  • str.find(' ', idx); 와 같은 형식으로 사용하면 idx번째 인덱스를 포함해서 처음으로 존재하는 공백의 인덱스를 반환!!!!!
  • 문자열의 경우 해당 문자열이 시작하는 인덱스 반환!!!
string str1 = "hi my name is gildong";

cout << str1.find(' ') << "\n";  //  2 출력
cout << str1.find(' ', 2) << "\n"; // 2 출력
cout << str1.find(' ', 3) << "\n"; // 5 출력
cout << str1.find("is") << "\n"; // 11 출력


< 특정 문자열 지우기 >

  • erase 사용 : O(n)이 걸리므로 시간 초과 보면서 사용하기
  • pop_back() : 맨 뒤 문자를 하나 제거!! (vector 과 유사)
#include <iostream>
#include <string>

using namespace std;

string test = "[]";
string test2 = "hello";
	
test.erase(test.length() - 1, 1); 
// (지우기 시작하는 index, 지울 문자 개수)
test.erase(0, 1);

cout << test << "\n"; // 빈 문자열 출력!!
cout << test.length(); // 0 출력!!

test2.erase(1, 3); // 인덱스 1 포함해서 3개 지우기
cout << test2; // ho 출력


< 문자열 분할 >

  • streamstring 사용

  • #include < sstream > 삽입!!

    1. 공백을 기준으로 분리하고 싶은 경우
    1. 특정 문자를 기준으로 분리하고 싶은 경우 -> getline 사용
      특정 문자가 포함되어 있지 않으면 전체 문자열 출력
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	string str1 = "hi my name is gildong";

	stringstream ss1(str1), ss2(str1);
	string token;

// 1. 공백 기준 분리
	while (ss1 >> token)
		cout << token << "\n";

	cout << "-----\n";

// 2. 특정 문자 기준 분리 -> getline 사용!
	while (getline(ss2, token, 'i'))
		cout << token << "\n";

	return 0;
}



< 문자열 할당 >

string a = "123";
string b = a;

a = a.substr(0, 1);  // b에는 영향 없다!!!

cout << a << "\n" << b;

// 출력
1
123


< 문자열 <-> 정수형 변환 >

#include <iostream>
#include <string>
#include <sstream>

using namespace std;


int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	string str1 = "1000";


	// string -> int
	int num = atoi(str1.c_str());  


	// int -> string
	string str2 = to_string(num); 
	
    
    cout << num + 1 << "\n";  // 1001 출력

	cout << str2; // 1000 출력

	return 0;
}


< 문자열 비교 >

  • 문자열이 값이 같은지 비교하고 싶은 경우에는 == 연산자를 사용하자!!


<문자열 추출 >

  • string 클래스의 substr(시작index, 문자 개수) 사용

  • string::substr()은 항상 새로운 메모리를 할당해서 리턴한다

  • substr(index) -> index 부터 마지막까지 를 반환!!



< 소문자 <-> 대문자 변환 >

  • #include < ccytpe > 추가
  • toupper, tolower 사용
#include <string>
#include <cctype>
#include <iostream>

using namespace std;

int main(void){
    
    char aaa = '3'; // 소문자, 대문자 아닌 경우에는 그대로 리턴
    aaa = toupper(aaa);
    cout << aaa << "\n";

    char bbb = 'A';
    bbb = tolower(bbb);
    cout << bbb;

    return 0;
}

/* 출력
3
a
*/

< 문자열 뒤집기 >

  • algorithm 헤더파일의 reverse 사용
#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

int main() {
  
    string str = "abcde";
    reverse(str.begin(), str.end());

    cout << str;
}

//출력
edcba

< 문자열 맨 앞,뒤 문자 접근 및 마지막 문자 제거하기 >

  • string.front()
  • string.back()
  • string.pop_back()
#include <string>
#include <iostream>

using namespace std;

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

    cout << str.front() << "\n";
    cout << str.back() << "\n";

    str.pop_back();
    cout << str.back() << "\n";
}

//출력
a
e
d

profile
매 순간 최선을 다하자

0개의 댓글