아이공의 AI 공부 도전기

[C++] 문자열 관련 정리 (ASCII, string 헤더파일 함수)

 

     

 

문자열과 관련하여 2가지 방식이 있다고 본다.

1)  char array 형태 (배열 형태)

2) #include string -> string str 방식

 

이와 관련하여 기초적인 부분에 대해 정리를 하고 보자

 

1. ASCII 코드 변환

기본적으로 ASCII 코드 변환은 굳이 string을 쓰지 않아도 되며 배열을 쓸 필요도 없다. 단순히 char를 쓰거나 ASCII에 해당하는 숫자를 통해서 표현이 가능하다.

 

ASCII Chart는 다음과 같다.

https://en.cppreference.com/w/cpp/language/ascii

이에 따라 다음과 같은 코드를 돌리면 아래 주석과 같은 출력을 확인할 수 있다.

 

#include <iostream>
using namespace std;
int main(){	
	for (int i=97; i<100; i++){
		cout << i << " " << char(i) << endl;		
	}	
    /* 출력 결과
    97 a
    98 b
    99 c
    */
}

물론 이를 응용하여 숫자로 변환하는 방법으로 다음과 같이 나타낼 수 있다.

 

#include <iostream>
using namespace std;
int main(){	
	char a[3] = {'a', 'g', 'z'};
	for (int i=0; i<3; i++){
		cout << a[i]-'a' << endl;		
	}	
	/* 
	0
	6
	25 
	*/
}

상황에 따라서는 숫자 또한 가능 숫자 값을가지는 아래 배열에 '0'을 빼는 것으로 숫자의 차이를 나타낼 수 있다.

a[i]-'0'

 

https://www.acmicpc.net/problem/11720 를 통해 연습을 할 수 있다.

 

2. string 클래스 헤더파일을 활용한 다양한 함수 접근

 

#include <string>을 통해 문자열 string을 활용할 수 있다. 문자열의 길이는 동적 변경 가능

더불어 이를 통한 다양한 함수에도 접근이 가능하다.

 

2-1) length, size, capacity, clearstr.size() : string의 사이즈 반환

 

str.length() : string의 길이 반환 (size와 같은 값 반환)

str.capacity() : string에 할당된 메모리 크기를 반환

str.resize(int n) : n개의 크기로 만듬.(string의 길이가 n보다 길면 절삭, 짧으면 빈공간으로 채움)

str.resize(int n, char s) : n개의 크기로 만듬. sting의 길이보다 n이 더 길 경우 char s로 채움

str.clear() : string 문자열을 지움. size, length = 0, 0

 

#include <iostream>
#include <string>
using namespace std;
int main(){	
	string str = "abcde";
	cout << "size : " << str.size() << endl; //5
	cout << "length : " << str.length() << endl; //5 
	cout << "capacity : " << str.capacity() << endl; //5
	str.resize(3);
	cout << "resize 3 : " << str << endl; //abc
	str.resize(7,'z');
	cout << "resize 7 : " << str << endl; //abczzzz
	
	cout << "size : " << str.size() << endl; //7
	cout << "length : " << str.length() << endl; //7
	cout << "capacity : " << str.capacity() << endl; //10
	
	str.clear();
	cout << "size : " << str.size() << endl; //0
	cout << "length : " << str.length() << endl; //0
	cout << "capacity : " << str.capacity() << endl; //10		
}

 

2-2) at, front, back

 

str[index] : index에 해당하는 char 반환

str.at(index) : index에 해당하는 char 반환

str.front() : 맨 앞 char 반환

str.back() : 맨 뒤 char 반환

#include <iostream>
#include <string>
using namespace std;
int main() {
	string str = "abcde";
	cout << "normal index method : " << str[3] << endl; //d
	cout << "at : " << str.at(2) << endl; //c
	cout << "front : " << str.front() << endl; //a
	cout << "back : " << str.back() << endl; //e		
}

 

2-3) append, insert, replace, erase

 

+를 활용한 문자열 합치기 : string + string 형태

str.append(str2) : str과 str2를 합쳐 str에 저장함.

str.append(str2, i, j) : str과 str2를 합친다. 다만 이 때 str2의 i index부터 j개를 합치는 것으로 본다. 아래 예에서 확인할 수 있듯이 "abcde"라는 str과 "fghi"라는 str2가 존재하고 str2의 1번째 index 즉, "g"부터 2개 즉, "gh"를 str과 합친다고 보면 된다. 결과는 보이듯이 "abcde" + "gh" = "abcdegh"이다.

str.insert(i, str2) : str에 str를 삽입한다. 다만 써넣는 숫자는 str의 몇 번째 index에 넣을지를 설명한다. 아래 예에서 확인할 수 있듯이 3번째 index 즉, str에서는 "abc" 다음에 str2를 넣는다고 본다. 결과는 보이듯이 "abc"+"fghi"+"de" = "abcfghide"이다.

str.replace(i, j, str2) : i번째 index부터 j개의 str을 str2로 교체한다. 아래 예에서 확인할 수 있듯이 str 2번째 index부터 2개 즉, "cd"를 str2 "fghi"로 교체한다. "ab"+"fghi"+"e" = "abfghie"이다.

 

#include <iostream>
#include <string>
using namespace std;
int main(){	
	string str = "abcde";
	cout << "+ : " << str + "fghi" << endl; // "abcdefghi"
	cout << "append(str2) : " << str.append("fghi") << endl; // "abcdefghi"
	str = "abcde";
	cout << "append(str2, i, j) : " << str.append("fghi", 1, 2) << endl; // "abcdegh"
	str = "abcde";
	cout << "insert(i, str2) : " << str.insert(3, "fghi") << endl; // "abcfghide"
	str = "abcde";
	cout << "replace(i, j, str2) : " << str.replace(2, 2, "fghi") << endl; // "abfghie"		
}

 

2-3) find, substr

 

str.find() : 특정 문자열이 있는지를 확인하여 첫번째 index를 반환함. 만약 존재하지 않으면 최대값을 나타내며 int를 통해 감싸면 틀렸을 때 -1이 반환됨

str.substr() : str 전체 반환

str.substr(i) : str i번째 index부터 끝까지 반환

str.substr(i ,j) : str i번째 index부터 j개의 문자를 반환

 

#include <iostream>
#include <string>
using namespace std;
int main(){	
	string str = "abcde";	
	cout << "find : " << str.find("c") << endl; // 2	
	cout << "find : " << str.find("cd") << endl; // 2	
	cout << "find : " << str.find("ce") << endl; // 18446744073709551615	
	cout << "find : " << str.find("z") << endl; // 18446744073709551615
	cout << "find : " << int(str.find("z")) << endl; // -1
	cout << "substr : " << str.substr() << endl; // "abcde"	
	cout << "substr(i) : " << str.substr(3) << endl; // "de"	
	cout << "substr(i, j) : " << str.substr(3, 2) << endl; // "de"	
	cout << "substr(i, j) : " << str.substr(3, 5) << endl; // "de"
	}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading