C++
2017.02.14 13:12

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

조회 수 13266 댓글 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
번호 분류 제목 날짜 조회 수 추천 수
401 일반 배치파일(bat)에서 for루프 사용법 2010.04.15 47823 0
400 일반 배치파일(bat 파일) 명령어 사용법 2007.01.23 42993 61
399 C# 문자열 다루기 1 2012.04.06 18653 0
398 C# 문자열 검색 / 조작 2012.01.03 23560 0
397 Pi 무선랜 wifi 설정 2015.10.01 6974 0
396 LINUX 명령어 뒤의 옵션 자동완성 기능, complete 명령어 2015.01.06 8996 0
395 Android 맨날 까먹는 버튼 클릭 이벤트 핸들러 코드 2014.12.17 5964 0
394 LINUX 매번 잊는다.. tar 풀기 : tar zxvf file 2 2009.04.14 36735 0
393 일반 마크다운 markdown (.md) 파일이란 2017.07.12 12406 0
392 업무 마이크로 버블 Micro Bubble 이란 2016.08.29 9480 0
391 MFC 리사이징 다이얼로그(Resizing dialog) 2008.03.24 46824 0
390 LINUX 리눅스의 기본 명령어들 2015.01.20 6781 0
389 LINUX 리눅스에서 특정작업 or 명령어 반복하기 Crontab 2014.11.10 10383 0
388 LINUX 리눅스 파일시스템 체크 하기 fsck(e2fsck) 사용법 2016.04.15 39951 0
387 LINUX 리눅스 커널리빌딩, 버젼확인, ctags명령, vi편집기활용, 기본명령 2012.05.07 15048 0
목록
Board Pagination ‹ Prev 1 ... 3 4 5 6 7 8 9 10 11 12 ... 34 Next ›
/ 34

나눔글꼴 설치 안내


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

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

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5