随笔 - 4  文章 - 4  trackbacks - 0
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(2)

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

自己写了一个:
/***********begin test file***********/
#include <iostream>
#include <string>

int main()
{
 std::string str1 = "   hello world!   ";
 std::string trimstring = " ";
 std::cout << "str = \"" << str1 << "\"" << std::endl;
 std::cout << "str.find_first_of(' ')     : " << str1.find_first_of(trimstring)     << std::endl;
 std::cout << "str.find_first_not_of(' ') : " << str1.find_first_not_of(trimstring) << std::endl;
 std::cout << "str.find_last_of(' ')     : " << str1.find_last_of(trimstring)      << std::endl;
 std::cout << "str.find_last_not_of(' ')  : " << str1.find_last_not_of(trimstring)  << std::endl;
 str1.erase(str1.find_last_not_of(trimstring)+1);
 std::cout << "after right trim : \"" << str1 << "\"" << std::endl;
 str1.erase(0,str1.find_first_not_of(trimstring));
 std::cout << "after left trim  : \"" << str1 << "\"" << std::endl;
 return 0;
}
/***********end test file***********/

目前个人还没发现C,C++中有提供像Trim()那样的方法,
如有更好方法,还请各位大哥指点。

posted on 2007-11-04 15:43 希冀0714 阅读(7530) 评论(5)  编辑 收藏 引用 所属分类: C++

FeedBack:
# re: 求C++中:去掉字符串首尾空格的方法. 2007-11-04 19:10 lovedday
#include <string.h>
#include <stdio.h>

#pragma warning(disable : 4996)

char* rtrim(char* s)
{
if(s == NULL)
return NULL;

// set tail white space as '\0'
for(size_t i = strlen(s)-1; i >= 0 && s[i] == ' '; i--)
s[i] = '\0';

return s;
}

char* ltrim(char* s)
{
if(s == NULL)
return NULL;

char* p;

// skip head white space
for(p = s; *p == ' '; p++)
;

if(p != s) // if address p is not same as address s
{
size_t length = strlen(p);

if(length > 0) // so p is not null
{
memmove(s, p, length);
s[length] = '\0';
}
}

return s;
}

char* trim(char* s)
{
if(s == NULL)
return NULL;

rtrim(s);

return ltrim(s);
}

int main()
{
char s[10];
strcpy(s, " ab cde ");

trim(s);

printf("after trim:\n");

if(*s != '\0')
printf("%s, length = %d\n", s, strlen(s));
else
printf("s is null\n");

return 0;
}
  回复  更多评论
  
# re: 求C++中:去掉字符串首尾空格的方法. 2007-11-04 19:44 lovedday
#include <iostream>
#include <string>

using namespace std;

void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}

int main()
{
string str = " hello world! ";

trim(str);

cout << "after trim:" << endl;
cout << str << endl;

return 0;
}
  回复  更多评论
  
# re: 求C++中:去掉字符串首尾空格的方法. 2007-11-04 20:50 希冀0714
谢谢,这样的程序看起来清晰多了,学习中.  回复  更多评论
  
# re: 求C++中:去掉字符串首尾空格的方法. 2007-11-05 08:44 <a href=http://minidx.com>minidxer</a>
不错不错~~~,收下了。  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理