C++
2017.02.14 13:12

C++ string 정리 (C++ 문자열)

조회 수 13130 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

http://www.cplusplus.com/reference/string/string/



std::string

typedef basic_string<char> string;
String class
Strings are objects that represent sequences of characters.

The standard string class provides support for such objects with an interface similar to that of a standard container of bytes, but adding features specifically designed to operate with strings of single-byte characters.

The string class is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type, with its default char_traits and allocator types (see basic_string for more info on the template).

Note that this class handles bytes independently of the encoding used: If used to handle sequences of multi-byte or variable-length characters (such as UTF-8), all members of this class (such as length or size), as well as its iterators, will still operate in terms of bytes (not actual encoded characters).


Member types

member typedefinition
value_typechar
traits_typechar_traits<char>
allocator_typeallocator<char>
referencechar&
const_referenceconst char&
pointerchar*
const_pointerconst char*
iteratorrandom access iterator to char (convertible to const_iterator)
const_iteratorrandom access iterator to const char
reverse_iteratorreverse_iterator<iterator>
const_reverse_iteratorreverse_iterator<const_iterator>
difference_typeptrdiff_t
size_typesize_t


Member functions


Iterators:

Capacity:

Element access:

Modifiers:

String operations:

Member constants


Non-member function overloads


-------------------------------------------------------------------------------------------------


http://makerj.tistory.com/127


C++ string 정리 (C++ 문자열)

C++11 환경에서 정리한 글입니다 
또한 using namespace std를 한 상태임을 밝힙니다

이 글을 통해 std::string을 간략하게 정리한다.

string 생성


방법1

string myString = "abcd"; 
단, 이 방식으로는 'a'와 같은 char로 생성이 불가능하다. 따라서 이 한계를 극복하려면 방법 2를 써야한다.

방법2

string myString;
myString = "abcd";

string 확장, 문자열 추가


방법1: += 연산자 이용

string base = "hello world!";
base += "x";

방법2: append() 멤버 함수 이용

string base = "hello world!";
base.append("appended!");

string 길이


string base = "hello world!";
base.length();
base.size();

size()와 length()는 이름만 다를 뿐 같은 일을 하는 멤버 함수다.

메모리 관련


capacity()

string base = "hello world!";
base.capacity();

capacity()는 해당 문자열이 재할당을 하지 않고도 저장할 수 있는 문자열의 길이를 반환한다. 
문자열은 문자열이 늘어났을 때, 현재 capacity보다 클 경우 더 큰 메모리를 사용할 수 있도록 재할당된다.

max_size()

string base = "hello world!";
base.max_size();

myString.max_size()는 최대한 메모리를 할당했을 경우, 저장할 수 있는 문자열의 길이를 반환한다.

string의 특정 위치 문자 받기(charAt)


string base = "hello world!";
base.at(0); // 'h'
base.at(1); // 'e'

해당 위치의 char를 반환한다. 
java의 String.charAt()과 같다.

string에 있는 특정 문자 탐색


string base = "hello world!";
base.find("world!");

world! 문자열이 발견된 첫 위치를 반환한다.

if (base.find("world!") != string::npos) {
    // "world!"라는 문자열을 찾았을 때의 동작
}

탐색에 실패할 경우는 if 문에서 볼 수 있듯이 string::npos를 반환한다.

string간의 문자열 복사


string src = "I am source :)";
string dst;
dst = src;

dst에는 같은 내용이 복사되어 들어간다. 
얕은 복사가 아니다. 깊은 복사다. 즉, 복사 후에 src의 내용이 변경된다고 해도 dst의 내용에는 아무 영향을 끼치지 않는다.

string간의 문자열 비교


string a = "I am string one! ;)";
string b = "string 
if (a.compare(b) == 0) {
    // 두 문자열이 같을 때
} else if (a.compare(b) < 0) {
    // a가 b보다 사전순으로 앞일 때
} else if (a.compare(b) > 0) {
    // a가 b보다 사전순으로 뒤일 때
}

string의 문자열 대체하기 (replace기능)


http://stackoverflow.com/a/14678964/2050087 참조

Immutable Replace

원본 문자열에는 아무 영향을 끼치지 않는다. 변경된 문자열은 함수의 반환값으로 돌아온다.

#include <string>
#include <iostream>
using std::string;
std::string replaceString(std::string subject, const std::string &search, const std::string &replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
        subject.replace(pos, search.length(), replace);
        pos += replace.length();
    }
    return subject;
}

Mutable Replace

원본 문자열을 수정한다. 속도가 우선일 경우 사용하자.

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
        subject.replace(pos, search.length(), replace);
        pos += replace.length();
    }
}

타입 변환


문자를 다른 타입으로 변경해야 할 필요가 있는 경우는 흔하다. 그래서 C++11에 들어 표준 라이브러리에 기본적인 타입 변환 기능이 추가됐다.

개발환경이 C++11을 지원해야 한다.

// int ---> string
string s;
int i = 10;
s = std::to_string(i);
// string ---> int
string s = "123";
int i;
i = std::stoi(s);


Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
461 LINUX gdb 쓸때 상용구 secret 2019.06.26 0 0
460 Pi 라즈베리파이 내 작업 명령 secret 2019.06.10 0 0
459 일반 범용 레지 스터(eax, ebx, ecx, edx, esi, edi, esp, ebp) 2019.06.03 9928 0
458 Python 디렉토리 없으면 만들기 2019.03.30 5885 0
457 Python 줄 바꿈 없이 출력하는 방법 2019.03.30 6964 0
456 LINUX Ubuntu에서 Python 버전을 변경하는 방법 2019.03.29 12185 0
455 Python Google Colab에서 파일 업로드/다운로드 팁 2019.03.06 36550 0
454 Python pandas, matplot 자주사용하는 코드 2019.03.06 4992 0
453 Python matplot에서 한글이 보이도록 하는 코드 2019.03.06 6136 0
452 일반 OMV (OpenMediaVault) 플러그인들 2019.02.10 8033 0
451 일반 ddns 정보 secret 2019.02.10 0 0
450 Android git archive 를 사용해서 폴더를 .git 제외하고 tar 나 zip 으로 묶기 1 2019.02.10 7198 0
449 LINUX vi 설정하기(.vimrc) 2019.02.01 5523 0
448 Pi 칩 저항 사이즈표, 사이즈변환, 와트, 오차표 2019.01.11 10587 0
447 Pi NPN과 PNP 트랜지스터의 차이 2019.01.03 13991 0
목록
Board Pagination ‹ Prev 1 2 3 4 5 6 7 8 9 10 ... 34 Next ›
/ 34

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5