Programming/c++

[c++] trim( ), 공백, 개행, 탭 제거 (whitespace 제거)

owls 2023. 6. 15. 14:06
728x90

java에서는 trim( ) 함수를 제공하지만 C++에서는 boost 라이브러리 사용하지 않으면 제공하지 않습니다.

그래서 trim( )처럼 사용하기 위한 예제들을 포스팅하겠습니다~

 

문자열의 왼쪽(선행), 오른쪽(후행)에 whitespace가 있다면 제거하는 방법입니다.

 

Whitespace

문자
유니코드
이름
약칭
 
U+0020
space
SPC
\t
U+0009
horizontal tab
TAB
\n
U+000A
newline
LF
\v
U+000B
vertical tab
VT
\f
U+000C
feed
FF
\r
U+000D
carriage return
CR

 

ASCII Code

이름 10진 16 문자
horizontal tab 9 0x09 HT
newline 10 0x0A LF
vertical tab 11 0x0B VT
feed 12 0x0C FF
carriage return 13 0x0D CR
space 32 0x20 SP

1. find_first_not_of( ), find_last_not_of( )

string 변수에 삭제하려고하는 whitespace를 선언하여 사용합니다.

#include <algorithm>

const std::string WHITESPACE = " \n\r\t\f\v";

std::string ltrim(const std::string &s) {
	size_t start = s.find_first_not_of(WHITESPACE);
	return (start == std::string::npos) ? "" : s.substr(start);
}

std::string rtrim(const std::string &s) {
	size_t end = s.find_last_not_of(WHITESPACE);
	return (end == std::string::npos) ? "" : s.substr(0, end + 1);
}

std::string trim(const std::string &s) {
	return rtrim(ltrim(s));
}

int main() {

	std::string s = "\n\tHello World  \r\n";
	printf("[%s]", trim(s).c_str());

	return 0;
}

[Hello World]

 

2. std::isspace

헤더 파일

#include <cctype>

 

함수 프로토타입

int isspace(char c)

 

return

0 : whitespace아님
whitespace 해당 ascii 10진수 값

 

예제

#include <iostream>
#include <cctype>
#include <string>

std::string trim(const std::string &s)
{
	auto start = s.begin();
	while (start != s.end() && std::isspace(*start)) {
		start++;
	}

	auto end = s.end();
	do {
		end--;
	} while (std::distance(start, end) > 0 && std::isspace(*end));

	return std::string(start, end + 1);
}

int main() {
	std::string s = "\n\tHello World  \r\n";
	printf("[%s]", trim(s).c_str());

	return 0;
}

[Hello World]

 

 

isspace 공식 문서

3. std::regex_replace

 

헤더 파일

#include <regex>

 

예제

#include <regex>

std::string ltrim(const std::string &s) {
	return std::regex_replace(s, std::regex("^\\s+"), std::string(""));
}

std::string rtrim(const std::string &s) {
	return std::regex_replace(s, std::regex("\\s+$"), std::string(""));
}

std::string trim(const std::string &s) {
	return ltrim(rtrim(s));
}

int main() {
	std::string s = "\n\tHello World  \r\n";
	printf("[%s]", trim(s).c_str());

	return 0;
}

[Hello World]

 

 

728x90