gwuj 发表于 2015-12-1 05:10:07

【C++实现python字符串函数库】strip、lstrip、rstrip方法

std::string do_strip(const std::string &str, int striptype, const std::string&chars)  {
  std::string::size_type strlen = str.size();
  std::string::size_type charslen = chars.size();
  std::string::size_type i, j;
  
  //默认情况下,去除空白符
  if (0 == charslen)
  {
  i = 0;
  //去掉左边空白字符
  if (striptype != RIGHTSTRIP)
  {
  while (i < strlen&&::isspace(str))
  {
  i++;
  }
  }
  j = strlen;
  //去掉右边空白字符
  if (striptype != LEFTSTRIP)
  {
  j--;
  while (j >= i&&::isspace(str))
  {
  j--;
  }
  j++;
  }
  }
  else
  {
  //把删除序列转为c字符串
  const char*sep = chars.c_str();
  i = 0;
  if (striptype != RIGHTSTRIP)
  {
  //memchr函数:从sep指向的内存区域的前charslen个字节查找str
  while (i < strlen&&memchr(sep, str, charslen))
  {
  i++;
  }
  }
  j = strlen;
  if (striptype != LEFTSTRIP)
  {
  j--;
  while (j >= i&&memchr(sep, str, charslen))
  {
  j--;
  }
  j++;
  }
  //如果无需要删除的字符
  if (0 == i&& j == strlen)
  {
  return str;
  }
  else
  {
  return str.substr(i, j - i);
  }
  }
  
  }
  
页: [1]
查看完整版本: 【C++实现python字符串函数库】strip、lstrip、rstrip方法