본문 바로가기

ALGORITHM/개념

[c++] string 문자열

#include <string> 

문자열에 대해 파헤쳐 봅시다 ~

 

ASCII 코드

가장 많이 쓰는 알파벳을 알아봅시다.

A : 65

a : 97

 

리턴값

front, back

맨 앞 문자와 맨 뒤 문자를 뽑아주는 함수입니다.

 

begin, end

맨 앞 iterator, 맨 뒤 iterator 입니다.

 

find

특정 문자열을 찾으면 시작 위치를 리턴

더보기

first 'needle' found at: 14

second 'needle' found at: 44

'haystack' also found at: 30

Period found at: 51

There are two prepositions in this haystack with needles.

 

뒤에 붙는 숫자는 그 문자열부터 시작한다.

// string::find
#include <iostream>       // std::cout
#include <string>         // std::string

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

  return 0;
}

 

first 'needle' found at: 14

second 'needle' found at: 44

'haystack' also found at: 30

Period found at: 51

There are two prepositions in this haystack with needles.

 

뒤에 붙는 숫자는 그 문자열부터 시작한다.

 

substr

문자열의 일부를 리턴한다.

더보기
// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

 

think live in details.

 

변경

append, insert

더보기
// appending to string
#include <iostream>
#include <string>

int main ()
{
  std::string str;
  std::string str2="Writing ";
  std::string str3="print 10 and then 5 more";

  // used in the same order as described above:
  str.append(str2);                       // "Writing "
  str.append(str3,6,3);                   // "10 "
  str.append("dots are cool",5);          // "dots "
  str.append("here: ");                   // "here: "
  str.append(10u,'.');                    // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append<int>(5,0x2E);                // "....."

  std::cout << str << '\n';
  return 0;
}

 

1. 문자열 추가

2. str3의 6번째 문자열부터 3번째까지 추가

3. 문자열 5번째까지 추가

4. 문자열 추가

5. ..? .을 10번 추가하는 것 같은데 u를 모르겟네요

6. 문자열 8번째 부터 마지막까지 추가

 

더보기
// inserting into a string
#include <iostream>
#include <string>

int main ()
{
  std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )

  std::cout << str << '\n';
  return 0;
}

 

1. 6번째에 str2 추가

2. 6번째에 str3의 3번째부터 4개까지 추가

3. 10번째에 문자열의 8번째까지 추가

4. 10번째에 문자열 추가

5. 15번째에 1개 문자열 추가?

6. 5번째 문자열에 , 추가

7. 마지막에 . 세개 추가

 

 

push_back

문자열 뒤에 문자열 추가

 

erase

문자열 지우기

더보기
// string::erase
#include <iostream>
#include <string>

int main ()
{
  std::string str ("This is an example sentence.");
  std::cout << str << '\n';
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '\n';
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '\n';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '\n';
                                           // "This sentence."
  return 0;
}

 

This is an example sentence.

This is an sentence.

This is a sentence.

This sentence.

 

1. 10번째 문자부터 8개 삭제

2. 9번째 문자를 지운다

 

replace

더보기
// replacing in a string
#include <iostream>
#include <string>

int main ()
{
  std::string base="this is a test string.";
  std::string str2="n example";
  std::string str3="sample phrase";
  std::string str4="useful.";

  // replace signatures used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  std::string str=base;           // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string." (1)
  str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
  str.replace(8,10,"just a");     // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

  // Using iterators:                                               0123456789*123456789*
  str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
  str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
  std::cout << str << '\n';
  return 0;
}

 

replace is useful.

 

1. 9번째부터 5개까지 str2로 치환

2. 19번째부터 6개까지 str3의 7번째부터 6개까지로 치환

3. 8번째부터 10개까지 문자열로 치환

4. 8번째부터 6개까지 문자열의 7번째까지로 치환

5. 22번째부터 1개를 문자열 3번 반복해서 치환

 

swap

문자열을 변경하는 함수

 

pop_back

맨 뒤 문자 하나 제거하는 함수

 

'ALGORITHM > 개념' 카테고리의 다른 글

[Java] 순열, 조합, 부분집합  (0) 2021.08.12
트라이 Trie (c++ 구조체 구현)  (0) 2021.07.17
[c++] unordered_set / unordered_map  (0) 2021.05.10
[c++] stack, queue  (0) 2021.04.16