string class 에서 ltrim,rtrim,trim 을 구현하고 싶습니다.

linuxqna의 이미지

요즘 C++을 쓰고 있는데
C에서는 pointer를 이용해서 ltrim, rtrim, trim 을 구현해서 쓰곤했는데
혹시 C++의 string class 에서 이걸 쉽게 구현할 방법이 있을까요 ?

string name("   KLDP BBS    ");

요기서 name의 앞뒤의 white space를 잘라내고 싶습니다.
string class의 member function을 조합하면 될것 같기도 한데.

아무튼 조언 부탁드립니다.

ageldama의 이미지

단순하게 사용하시던 방법으로 하셔도 될텐데요. c_str().

좀 더 깔끔하게는 iterator로 검색하면서 string::erase()랑해서 지우시는걸로 구현하셔도 될듯.

#include <iostream>
#include <string>
using namespace std;


int main(int argc, char *argv[])
{
	string s="  kldp ?  ";

	cout << "[" << s << "]" << endl;

	//ltrim
	//탭이나 스페이스에 각각.
	{
		string::iterator it_begin = s.begin();
		string::iterator it_end(it_begin);
		for ( ; (*it_end) == ' ' ; it_end++ )
			;
		s.erase(it_begin, it_end);

		cout << "[" << s << "]" << endl;
	}

	//rtrim
	{
		string::reverse_iterator it_begin = s.rbegin();
		string::reverse_iterator it_end(it_begin);
		for ( ; (*it_end) == ' ' ; it_end++ )
			;
		s.erase(s.length() + (it_begin - it_end), (it_end - it_begin));

		cout << "[" << s << "]" << endl;
	}

	return 0;
}

## 아래에 달린 링크보니 저렇게 우아하게도!^^;

----
The future is here. It's just not widely distributed yet.
- William Gibson

lacovnk의 이미지

출처는 위의 링크 ( http://www.borlandforum.com/impboard/impboard.dll?action=read&db=cpp_tip&no=1 ) 입니다

inline string trim_left(const string& str)
{
    string::size_type n = str.find_first_not_of(" \t\v\n");
    return n == string::npos ? str : str.substr(n, str.length());
}

inline string trim_right(const string& str)
{
    string::size_type n = str.find_last_not_of(" \t\v\n");
    return n == string::npos ? str : str.substr(0, n + 1);
}
string trim(const string& str){return trim_left(trim_right(str));}

int로 선언되어있는 position용 변수 n의 type을 string::size_type로 바꾸었습니다. find()의 리턴 형이 저것 맞지요? :)

doldori의 이미지

lacovnk wrote:
int로 선언되어있는 position용 변수 n의 type을 string::size_type로 바꾸었습니다. find()의 리턴 형이 저것 맞지요? :)

네. int를 쓰면 오동작할 수도 있어요.
비슷하지만 string::size_type 대신 iterator를 쓰는 방법입니다.
string trim_left(const string& str) 
{ 
    string::const_iterator it = find_if(str.begin(), str.end(), not1(ptr_fun(::isspace)));
    return string(it, str.end());
} 

string trim_right(const string& str) 
{ 
    string::const_reverse_iterator it = find_if(str.rbegin(), str.rend(), not1(ptr_fun(::isspace)));
    return string(str.begin(), it.base());
} 
kcando의 이미지

boost 라이브러리를 참고하세요.

http://boost.org/doc/html/string_algo/usage.html#id1290955

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.