C++
2017.02.14 13:12

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

조회 수 13393 댓글 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
번호 분류 제목 날짜 조회 수 추천 수
236 LINUX [Shell Script] Shell 스크립트에서 매개변수 치환 2014.09.23 29878 0
235 LINUX [Shell Script] 파일을 한줄씩 읽어오기 2014.10.03 56584 0
234 Android logcat, main+kernel로그 합치는 로그 2014.10.07 10480 0
233 일반 배치파일(bat)에서 날짜-시간을 파일 명으로 쓰기 2014.10.10 29457 0
232 Android 에러 넘버 ErrorNo in Linux 2014.10.14 9612 0
231 C# C# 배열 array 2014.10.22 12737 0
230 LINUX [Shell Script] 쉘 스크립트에서의 사칙연산과 문자열 자르기 2014.11.01 82010 0
229 LINUX [Shell Script] 쉘 스크립트에서 getopt 사용하는 법 2014.11.09 17131 0
228 LINUX 리눅스에서 특정작업 or 명령어 반복하기 Crontab 2014.11.10 10500 0
227 LINUX shell 에서 background로 명령어 수행하기 2014.11.11 37375 0
226 Android L버전 32/64bit tip 및 multi user 관련 adb 명령어 2014.11.18 8597 0
225 업무 Force To Crash Guide 강제로 Crash 내기 secret 2014.11.27 0 0
224 Android ion memory 사용량 확인하기 2014.12.03 9037 0
223 업무 SurfaceFlinger dump 하기 secret 2014.12.04 0 0
222 업무 ION memory allocator secret 2014.12.15 0 0
목록
Board Pagination ‹ Prev 1 ... 14 15 16 17 18 19 20 21 22 23 ... 34 Next ›
/ 34

나눔글꼴 설치 안내


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

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

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5