티스토리 뷰

언어/C++

17.1 std::string과 std::wstring

js0331 2020. 5. 25. 15:55
#include<iostream>
#include<string>
#include<locale>
#include<cstddef>

int main()
{
	// c-style
	{
		char *strHello = new char[7];
		strcpy_s(strHello, sizeof(char) * 7, "Hello!");
		std::cout << strHello << std::endl;
	}
	
	// basic_string<>
	{
		//char가 들어가면 string
		std::string string;
		//wchar_t가 들어가면 wstring
		std::wstring wstring;
		
		//그러면 wchar_t는 머가 다른걸까?
		wchar_t wc; // wide-character/unicode
		// 국제어를 표현할때 주로 사용!
	}
}

 

 

std::string

 

#include<iostream>
#include<string>
#include<vector>

int main()
{
    // const char * my_string = "my string";
	std::string my_string("my string");
	
	std::string second_string(my_string, 3, 4);
	
	std::cout << second_string << std::endl;
	
	return 0;
}
stri

 

#include<iostream>
#include<string>
#include<vector>

int main()
{
	// const char * my_string = "my string";
	// std::string my_string("my string");
	
	std::vector<char> vec;
	for(auto e : "Today is a good day.")
		vec.push_back(e);
	
	// std::string second_string(my_string, 3, 4);
	std::string second_string(vec.begin(), vec.end());
	
	std::cout << second_string << std::endl;
	
	return 0;
}
Today is a good day.

 

 

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

int main()
{
	// const char * my_string = "my string";
	// std::string my_string("my string");
	
	std::vector<char> vec;
	for(auto e : "Today is a good day.")
		vec.push_back(e);
	
	// std::string second_string(my_string, 3, 4);
	std::string second_string(vec.begin(), std::find(vec.begin(), vec.end(), 'i'));
	
	std::cout << second_string << std::endl;
	
	return 0;
}
Today 

 

 

#include<iostream>
#include<string>
#include<sstream>

// 머가 들어오든 string으로 바꿔서 리턴해줌
template <typename T>
std::string ToString(T x)
{
	std::ostringstream osstream;
	
	osstream << x;
	return osstream.str();
}

template <typename T>
bool FromString(const std::string & str, T &x)
{
	std::istringstream isstream(str);
	
	return (isstream >> x) ? true : false;
}

int main()
{
	std::string my_str(ToString(3.145234));
	
	// string -> int, float
	int i = std::stoi(my_str);
	float f = std::stof(my_str);
	
	if(FromString(my_str, i))
		std::cout << i << std::endl;
	else
		std::cout << "Cannot covert string to int" << std::endl;
	
	std::cout << my_str << std::endl;
	std::cout << i << std::endl;
	
	return 0;
}
3
3.14523
3

 

 

.c_str == .data

string my_str("abcdefg");

const char *arr = my_str.c_str();

cout << (int)arr[6] << endl;
cout << (int)arr[7] << endl;

return 0;

 

.copy 는 null character를 자동으로 넣어주지 않는다.

 

 

'언어 > C++' 카테고리의 다른 글

18.2 ostream으로 출력하기  (0) 2020.05.25
18.1 istream으로 입력 받기  (0) 2020.05.25
16.1 / 16.2 표준 템플릿 라이브러리, 컨테이너, 반복자 소개  (0) 2020.05.23
15.5 / 15.6 / 15.7  (0) 2020.05.23
15.2 오른쪽 값 참조  (0) 2020.05.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함