c++ 문자열 처리

JH Bang·2022년 12월 26일
0

C/C++

목록 보기
8/8

std::strin -> char const *

#include <string>

std::string cppStr = "hello";
char const *str = cppStr.c_str();

UpperCase, LowerCase

/* string 형 */
#include <string>
#include <cstring>

std::string mystrlower(std::string &str)
{
	std::string res;
	for (int i = 0; i < str.size();++i)
	{
		res.push_back(std::tolower(str[i]));
	}
	return res;
}

//char형에 적용할 때는 <cctype>

std::stoi()

숫자 문자열을 int, double로 변환

#include <string>

std::string num = "1234";
int N = std::stoi(num);

//std::stof (float), std::stod (double), std::stol (long long)

split 함수

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

std::vector<std::string> split(std::string input, char delim) {
    std::vector<std::string> vec;
    std::stringstream ss(input);
    std::string tmp;

    while (std::getline(ss, tmp, delim))
        vec.push_back(tmp);
    return (vec);
}

<sstream> 사용

std::istringstream

문자열에서 각 타입별로 추출(>>)할 때 사용한다.

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

int main() {
	std::istringstream iss("hello world 42");
	std::string s1, s2;
	int n;
	iss >> s1 >> s2 >> n;

	std::cout << s1 << "\n" << s2 << "\n" << n << "\n";
}
hello
world
42

std::ostringstream

하나의 문자열로 합치기만 가능하고, 추출(>>)할 수는 없다.

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

int main() {
	std::ostringstream oss;
	std::string s1 = "hello";
    std::string s2 = "world";
	int n = 42;
	oss << s1 << " " << s2 << " "<< n;
	std::cout << oss.str() << "\n";
}
hello world 42

std::stringstream

합(<<)치거나 추출(>>) 둘 다 할 때 사용한다.

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

int main() {
	std::string str = "hello world";
	std::stringstream ss("good time ");
	std::string s1;
	std::string s2;

	std::cout << ss.str() << "\n";
	ss << str << " this is " << 42;
	ss >> s1 >> s2;
	std::cout << "s1 : " << s1 << "\ns2 : " << s2 << "\n";

	ss << " yes " << 42;
	std::cout << ss.str() << "\n";
}
good time 
s1 : hello
s2 : world
hello world this is 42 yes 42
profile
의지와 행동

0개의 댓글